非空堆栈的java EmptyStackException
如何处理这段代码的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;
}
# 1 楼答案
由于以下代码行,出现了异常
在循环的第一次迭代期间,如果'expr'的第一个字符是运算符,则if中的条件变为true
但由于这是第一次迭代,堆栈中并没有任何要弹出的操作数
上述代码适用于'expr',例如12+在运算符之前有足够的操作数,但不适用于'expr',例如+12在运算符之前没有足够(2)个操作数
# 2 楼答案
我想,你应该在
stack.pop()
之前检查stack.length