【问题标题】:Exception thrown when using stack.pop in Java在 Java 中使用 stack.pop 时抛出异常
【发布时间】:2013-11-17 03:20:18
【问题描述】:

首先要记住 EXPRESSION 是“2 + 3 * 5”,而 POSTFIX 表达式是 2 3 5 * +
这是我编写的一个方法,用于从具有后缀表达式的堆栈中提取运算符和操作数,然后评估整个事物。

// This method evaluates the postFix expression
public void evaluateRPN() {

    int t1 = 0,
        t2 = 0,
        calculation = 0;
    String oper;

    double result;

    // Empty stack  
    Stack stack = new Stack();

    // Tokenize expression
    Scanner scan = new Scanner(this.postfix);
    char current;

    while ( scan.hasNext() ) {

        String token = scan.next();     

        if ( this.isNumber(token) ) { // if the token is an operand, push it onto the stack

            stack.push(token);


        } else {        // If the token is an operator          

            t1 = (char) stack.pop();
            t2 = (char) stack.pop();                

            calculation = (int) evalEx(t2, token, t1 );
            stack.push(calculation);    

        }

    }

    this.finalExpression = (String) stack.pop();

}

现在当我运行这段代码时,它给我一个错误: t1 = (char) stack.pop(); 我开始从堆栈中弹出第一个元素。此外 evalEx() 方法已经在其他地方声明并且它工作得很好。 所以我的问题是,我在这里缺少什么?我知道我应该在 (else) 部分使用 try/catch,但我认为这不是问题所在。 提前致谢!

【问题讨论】:

  • 它给出的错误是什么?

标签: java exception stack


【解决方案1】:

因为您将String 对象转换为char,这是不允许的。除非您正在使用非常旧的 java 编译器,否则请使用泛型。使用Stack<String> 而不是Stack,您将在编译时收到错误消息。此外,Stack 已被弃用。请改用Deque

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-10
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2019-07-19
    相关资源
    最近更新 更多