我正在尝试建立一种将后缀符号评估为答案的方法。例如(6 8 +)将为14。从堆栈中弹出元素后,我是否必须构建一个单独的方法来添加元素?
private static double computePostfix(String postfix) {
Scanner scan = new Scanner(postfix);
StackInterface<Double> stack = new ArrayStack<>();
// Read all tokens in the string expression
while(scan.hasNext()) {
String token = scan.next();
switch(token) { // Consider different values for token
case "+":
// Loops only through numbers for this addition operation
while(!Double.isNaN(stack.peek())) {
// TODO: pop and add up
Double sum =+ stack.pop();
}
stack.pop(); // Remove the NaN
// TODO: Push the sum back on the stack
stack.push(newEntry);
break;
case "*":
// TODO: Similar to +
break;
case "-":
// TODO: Hard, and has special cases
break;
case "/":
// TODO: Hard, and has special cases
break;
case "(":
// Indicates start of a new operation
stack.push(Double.NaN);
break;
case ")":
break;
default: // Should be a number
stack.push(Double.parseDouble(token));
}
}
scan.close();
double answer = stack.pop(); // Should only be one item: the answer
if(!stack.isEmpty()) {
// Crash program: this expression was invalid
throw new IllegalArgumentException();
}
return answer;
}
您的错误是Double sum =+ stack.pop();
变量sum
必须在while循环之前。并将拼写错误=+
更改为+=