【问题标题】:EmptyStackException for non empty stack非空堆栈的 EmptyStackException
【发布时间】: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 循环,因为输入中没有任何标记,然后您尝试弹出堆栈但那里什么都没有。如果输入中确实有标记,你为什么要对我们隐藏它们???
  • 另外,异常发生在哪里?您没有显示堆栈跟踪,这是当您遇到异常时要显示的最重要的内容。

标签: java exception stack


【解决方案1】:

异常是由于以下代码行引起的。

op2 = ((Integer) stack.pop()).intValue();
op1 = ((Integer) stack.pop()).intValue();

在循环的第一次迭代中,如果 'expr' 的第一个字符是运算符,则 if 内部的条件为真

if (isOperator(c)) //true

但由于是第一次迭代,堆栈中没有任何要弹出的操作数。

上面的代码适用于 'expr' 例如 1 2 + 在运算符之前有足够的操作数,但不适用于 'expr' 例如 + 1 2 在运算符之前没有足够的 (2) 个操作数。

【讨论】:

    【解决方案2】:

    我想,你应该在stack.pop()之前检查stack.length

    【讨论】:

    • 这不是一个答案,而是一个评论(或者它是一个答案?如果是,那就错了)。
    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 2016-07-07
    • 2012-10-15
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多