此程序可计算两位数以上的表达式
import java.util.Stack;
public class ExpressionEvaluator {
public int evaluate(String s) {
Stack<Integer> numbers = new Stack<>();
Stack<Character> operators = new Stack<>();
int i = 0;
char c = s.charAt(i);
while (c==' '){
i++;
c = s.charAt(i);
}
if (!In(c)) {
int d = c -'0';
i++;
while (i<s.length()&&!In(s.charAt(i))&&s.charAt(i)!=' '){
d=d*10+(s.charAt(i)-'0');
i++;
}
numbers.push(d);
} else {
operators.push(c);
i++;
}
while ( i != s.length()) {
c = s.charAt(i);
if(c == ' '){
i++;
continue;
}
if (!In(c)) {
int d = c -'0';
i++;
while (i<s.length()&&!In(s.charAt(i))&&s.charAt(i)!=' '){
d=d*10+(s.charAt(i)-'0');
i++;
}
numbers.push(d);
} else if (operators.isEmpty()) {
operators.push(c);
i++;
} else {
switch (Precede(operators.peek(), c)) {
case '<':
operators.push(c);
i++;
break;
case '>':
char theta = operators.pop();
int a = numbers.pop();
int b = numbers.pop();
numbers.push(evalSingleOp(b, a, theta));
break;
case '=':
operators.pop();
i++;
break;
}
}
}
while (!operators.isEmpty()){
char theta = operators.pop();
int a = numbers.pop();
int b = numbers.pop();
numbers.push(evalSingleOp(b, a, theta));
}
return numbers.pop();
}
public char Precede(char a, char b) {//判断操作符的优先级
switch (a) {//先算最厉害的
case '+':
case '-':
if ((b == '*') || (b == '/') || (b == '('))
return '<';
else
return '>';
case '/':
case '*':
if (b == '(')
return '<';
else
return '>';
case '(':
if (b == ')')
return '=';
else
return '<';
case ')':
return '>';
default:
throw new RuntimeException("运算符优先级错误");
}
}
public boolean In(char ch) {//判断是操作数还是操作符
int i;
char[] p = new char[]{'+', '-', '*', '/', '(', ')'};
for (i = 0; i < 6; i++)
if (ch == p[i]) return true;
return false;
}
private int evalSingleOp(int a, int b, char op) {//计算表达式
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
throw new IllegalStateException("Unexpected operator: " + op);
}
}
public static void main(String[] args) {
ExpressionEvaluator evaluator = new ExpressionEvaluator();
System.out.println("(1+3)*((2+5)-4)*2="+evaluator.evaluate("(1+3)*((2+5)-4)*2"));
System.out.println("1+3*2+5-4*2="+evaluator.evaluate("1+3*2+5-4*2"));
System.out.println("100*2*3="+evaluator.evaluate("100*2*3"));
}
}
结果如图