【发布时间】:2018-03-22 17:11:06
【问题描述】:
我如何处理这段代码的EmptyStackException?读取文件的某些部分后显示我的堆栈为空。我猜它与push() 和pop() 方法有关,但不确定。
Stack<Integer> stack = new Stack<Integer>();
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer(expr);
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
char c = token.charAt(0);
if (isOperator(c)) {
op2 = ((Integer) stack.pop()).intValue();
op1 = ((Integer) stack.pop()).intValue();
result = evalSingleOp(token.charAt(0), op1, op2);
stack.push(new Integer(result));
} else {
stack.push(new Integer(Integer.parseInt(token)));
}
}
result = ((Integer) stack.pop()).intValue();
return result;
}
【问题讨论】:
-
“说我的堆栈是空的,其实它不是。”所以你说 Java 运行时是骗子?当然,它与
push()和pop()有关。这些是唯一操纵堆栈的东西。要么您输入错误,要么您有逻辑错误。表现出更多的努力。 -
很简单。您从一个空堆栈开始,然后程序跳过 while 循环,因为输入中没有任何标记,然后您尝试弹出堆栈但那里什么都没有。如果输入中确实有标记,你为什么要对我们隐藏它们???
-
另外,异常发生在哪里?您没有显示堆栈跟踪,这是当您遇到异常时要显示的最重要的内容。