如何處理EmptyStackException
這段代碼?在閱讀文件的一部分後,顯示我的堆棧是空的。我猜它與push()
和pop()
方法有關,但不完全確定。EmptyStackException非空堆棧
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()'有關。那些是操縱堆棧的唯一東西。要麼你輸入錯誤,要麼你有邏輯錯誤。顯示更多的努力。 – Kayaman
很簡單。你從一個空的堆棧開始,然後程序跳過while循環,因爲輸入中沒有任何標記,然後你嘗試彈出堆棧,但沒有任何東西。如果輸入中確實存在令牌,**爲什麼要將它們隱藏起來?** – ajb
此外,異常發生在哪裏?您沒有顯示堆棧跟蹤,這是在發生異常時顯示的最重要的事情。 – Kayaman