import java.util.Stack;public class yufafenxi { public static void main(String[] args) {
int result = 0;
Stack stack1 = new Stack(); // 运算符栈
Stack stack2 = new Stack(); // 运算数栈
stack1.push('#');
char[] c = "3-2+4*5#".toCharArray(); //算数表达式
int i = 0;
while (c[i] != '#') {
if (!yunsuanfu(c[i])) { //是否是运算符
stack2.push(c[i]);
} else {
if (f(stack1.peek().toString().toCharArray()[0]) - g(c[i]) < 0) {
stack1.push(c[i]);
} else {
int a = 0, b = 0;
char op = stack1.peek().toString().toCharArray()[0];
stack1.pop();
a = stack2.peek().toString().toCharArray()[0];
stack2.pop();
b = stack2.peek().toString().toCharArray()[0];
stack2.pop();
switch (op) {
case '+':
result = b + a;
stack2.push(result);
break;
case '-':
result = b - a;
stack2.push(result);
break;
case '*':
result = b * a;
stack2.push(result);
break;
case '/':
result = b / a;
stack2.push(result);
break;
}
}
}
i++;
}
result = stack2.peek().toString().toCharArray()[0];
System.out.println(result);
} public static int f(char c) { // 左优先函数
switch (c) {
case '+':
return 2;
case '-':
return 2;
case '*':
return 3;
case '/':
return 3;
case '#':
return 0;
default:
return -1;
} } public static int g(char c) { // 右优先函数
switch (c) {
case '+':
return 2;
case '-':
return 2;
case '*':
return 3;
case '/':
return 3;
case '#':
return 0;
default:
return -1;
}
} public static boolean yunsuanfu(char c) { // 是运算符
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '#') {
return true;
}
return false;
}
}
为什么我输任意一个表达式,这程序运行的结果怎么总是53啊?请给位帮帮我啦!