问题
I have a program that is meant to take in a Queue<String> that contains the elements of a prefix operation (i.e. an operation that is stated "+ 4 2" instead of "4 + 2", which is infix), then output the integer answer (just assume that a double is never needed, okay?). It works correctly for any multiplication or division operation, but fails in any addition or subtraction operation, and worse, in an inconsistent manner. For example, the output to "- 5 1" is 5, which would suggest it's adding one extra integer, but the output to "- 5 2" is 2, which is one integer too low. I just don't understand where the logic to this error is?
public static int eval(Queue<String> s){
String a=s.toString();
String b= a.replaceAll("\\[","").replaceAll("\\]","").replace(", "," ");
StringBuilder c=new StringBuilder();
c.append(b);
c.reverse();
Stack<Integer> stack=new Stack<>();
for (int i=0; i<c.length();i++){
char current=c.charAt(i);
if (current==' ')
continue;
if (current=='*'||current=='/'||current=='+'||current=='-'){
Integer one = stack.pop();
Integer two = stack.pop();
Integer maybe;
switch (current){
case '+':
maybe=one+two;
case '-':
maybe=one-two;
case '*':
maybe=one*two;
case '/':
maybe=one/two;
break;
default:
maybe=one;
}
stack.push(maybe);
} else {
StringBuilder maybe=new StringBuilder();
while(Character.isDigit(current)){
maybe.append(current);
i++;
current=c.charAt(i);
}
i--;
Integer n=Integer.parseInt(maybe.reverse().toString());
stack.push(n);
}
}
return stack.pop();
}
}
Edit: Note: It also can only output simple two integer, one operator, equations, but I can understand how to change that.
来源:https://stackoverflow.com/questions/61691226/why-does-my-prefix-expression-evaluator-program-miscalculate-any-addition-or-sub