这个 EmptyStackException 继续弹出。不知不觉中,我的堆栈中没有任何内容,而是用户输入的第一个元素。但是,我不确定代码的缺陷在哪里。(很多地方)但我只需要修复这个错误。
import java.util.*;
public class stacks2 {
public static void main (String []args){
System.out.printf("Enter a math equation in reverse polish notation:\n");
//Create stack of Strings
Stack<String> rpnStack = new Stack<String>();
//Create Scanner
Scanner input = new Scanner(System.in);
//String in = input.next();
while(input != null) {
String in = input.next();
// Tokenize string based on spaces.
StringTokenizer st = new StringTokenizer(in, " ", true);
while (st.hasMoreTokens()) {
rpnStack.push(st.nextToken());
}
//Send stack to Calculation Method
calculate(rpnStack);
}
}
public static void calculate(Stack<String> stack) {
// Base case: stack is empty => Error, or finished
if (!stack.isEmpty())
// throw new StackUnderflowException("Empty Stack");
// Base case: stack has 1 element, which is the answer => finished
if (stack.size() == 1)
System.out.printf("Finished, Answer: %s\n",stack.peek());
// Recursive case: stack more elements on it.
if (stack.size() > 1){
String temp1 = stack.peek();
stack.pop();
String temp2 = stack.peek();
stack.pop();
String temp3 = stack.peek();
stack.pop();
if (temp3.equals("+")){
float resultant = Float.parseFloat(temp1) + Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
if (temp3.equals("-")){
float resultant = Float.parseFloat(temp1) - Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
else if (temp3.equals("*")){
float resultant = Float.parseFloat(temp1) * Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
else if (temp3.equals("/")){
float resultant = Float.parseFloat(temp1) / Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
else{
System.out.printf("Something severely has gone wrong.");
}
}
}
}
输入和错误:
:~ Home$ java stacks2
Enter a math equation in reverse polish notation:
4 5 * 6 -
Finished, Answer: 4
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:85)
at stacks2.calculate(stacks2.java:41)
at stacks2.main(stacks2.java:22)
显然,这只是第一个元素,这让我认为我在 17 处的 while 循环是原因。有什么见解吗?