首页 > 代码库 > Java 编程处理四则运算式(包含括号)
Java 编程处理四则运算式(包含括号)
package com.malakana.cal;
import android.annotation.SuppressLint;
import java.util.*;
public class Yunsuan {
Yunsuan(String str1) {
EvaluateExpression(str1);
}
@SuppressLint("UseValueOf")
public static String EvaluateExpression(String str) {
char[] a;
int i = 0;
a = str.toCharArray();
Stack<Float> OPND = new Stack<Float>();
Stack<Character> OPTR = new Stack<Character>();
OPTR.push(‘=‘);
float number = 0;
int decimalnum = 1;
boolean integer = false;
boolean decimal = false;
while (true) {
if (i == str.length())
break;
if (In(a[i]) == -1) {
number = number * 10 + (a[i] - 48);
integer = true;
if (decimal)
decimalnum = decimalnum * 10;
i++;
} else if (a[i] == ‘.‘) {
if (decimal)
return "ERROR";
decimal = integer = true;
i++;
} else if (In(a[i]) > -1 && In(a[i]) < 7) {
if (In(a[i]) == 1 && (i == 0 || In(a[i - 1]) == 4))
OPND.push(new Float(0));
if (integer) {
OPND.push(new Float(number / decimalnum));
number = 0;
decimalnum = 1;
integer = decimal = false;
}
switch (Precede(In(OPTR.peek()), In(a[i]))) {
case 2:
if (OPND.empty())
return "ERROR";
float x = OPND.pop();
if (OPND.empty())
return "ERROR";
float y = OPND.pop();
char theta = OPTR.pop();
if (In(theta) == 3 && x == 0)
return "ERROR";
OPND.push(new Float(Operate(y, theta, x)));
break;
case 1:
OPTR.pop();
i++;
break;
case 0:
OPTR.push(new Character(a[i]));
i++;
break;
case -1:
return "ERROR";
}
}
}
if (OPND.empty())
return "ERROR";
else
return ("" + OPND.peek());
}
public static int In(char t) {
int i = 0;
if (t > 47 && t < 58)
return -1;
switch (t) {
case ‘+‘:
i = 0;
break;
case ‘-‘:
i = 1;
break;
case ‘*‘:
i = 2;
break;
case ‘/‘:
i = 3;
break;
case ‘(‘:
i = 4;
break;
case ‘)‘:
i = 5;
break;
case ‘=‘:
i = 6;
break;
}
return i;
}
public static int Precede(int t1, int t2) {
int relationship[][] = { { 2, 2, 0, 0, 0, 2, 2 },
{ 2, 2, 0, 0, 0, 2, 2 }, { 2, 2, 2, 2, 0, 2, 2 },
{ 2, 2, 2, 2, 0, 2, 2 }, { 0, 0, 0, 0, 0, 1, -1 },
{ 2, 2, 2, 2, -1, 2, 2 }, { 0, 0, 0, 0, 0, -1, 1 } };
return relationship[t1][t2];
}
public static float Operate(float a, char theta, float b) {
float i = 0;
switch (theta) {
case ‘+‘:
i = a + b;
break;
case ‘-‘:
i = a - b;
break;
case ‘*‘:
i = a * b;
break;
case ‘/‘:
i = a / b;
break;
}
return i;
}
public static void main(String[] args) {
new Yunsuan(null);
}
}
Java 编程处理四则运算式(包含括号)