所以这是我的代码:
public double evaluate(){
Stack numbers = new Stack();
Stack operators = new Stack();
String[] divert = {};
String problem = "2 + 2 + 3";
divert = problem.split(" ");
for(int i = 0; i < divert.length; i++){
if(divert[i].equals("*") || divert[i].equals("/")|| divert[i].equals("+") || divert[i].equals("-")){
if(operators.peek().equals("*") || operators.peek().equals("/")){
int a = Integer.parseInt((String)numbers.pop());
int b = Integer.parseInt((String)numbers.pop());
String operand = (String)operators.pop();
numbers.push(doMath(b, operand, a));
}
else if ( divert[i].equals("+") || divert[i].equals("-")){
operators.push(divert[i]);
}
} else {
numbers.push(divert[i]);
}
}
while(!operators.empty()){
int a = Integer.parseInt((String)numbers.pop());
int b = Integer.parseInt((String)numbers.pop());
String operand = (String)operators.pop();
numbers.push(doMath(a, operand, b));
}
double endNumber = (double)numbers.pop();
return endNumber;
}
我不断收到奇怪的错误,一个告诉我嵌套 if 语句中的 if(operators.peek().equals... 位返回 EmptyStackException。我在尝试将弹出的数字 (endNumber) 强制转换为返回时遇到另一个错误它。我在将其转换为双精度时遇到了问题。
如果有人会看到这个并告诉我问题是什么以及解决问题的任何可能方法,那就太好了,因为我真的不明白为什么它会给我这些错误。
我知道删除 divert[i].equals("+")/("-") 消除了第一个错误的问题,但这对我正在做的事情不太有利。