【问题标题】:Postfix Expression Evaluator, pop method errorsPostfix Expression Evaluator,弹出方法错误
【发布时间】:2019-03-13 16:09:54
【问题描述】:

我正在尝试从用户那里获取一个表达式并对其进行评估,但我不断收到导致 arrayindexoutofboundsexceptions 和空指针异常的 pop 方法错误。我该如何解决这个问题,是否存在我遗漏的其他问题?谢谢

这是我的堆栈类

public class MyStack<E> {
private E[] data;
private int top;

public MyStack() {
    data = (E[]) (new Object[10]);
    top = -1;
}

public void push(E item) {
    top++;
    data[top] = item;
}

public E peek() {
    return data[top];
}

public E pop() {
    top--;
    return data[top + 1];
}

public boolean isEmpty() {
    return top < 0;
}
}

这里是评估器类

public class EvalPostfix {

private String post;

public EvalPostfix(String post) {
    this.post = post;
}

public int eval() {

    MyStack<Integer> stack = new MyStack<Integer>();
    Scanner tokens = new Scanner(post);
    int result = 0;

    while (tokens.hasNext()) {
        if (tokens.hasNextInt()) {
            stack.push(tokens.nextInt());
        } else {
            int right = stack.pop();
            int left = stack.pop();

            if (tokens.equals("+")) {
                result = left + right;
            } else if (tokens.equals("-")) {
                result = left - right;
            } else if (tokens.equals("*")) {
                result = left * right;
            } else if (tokens.equals("/")) {
                result = left / right;
            }
            stack.push(result);
        }
    }
    return stack.pop();
}
}

这里是主类

public class Prog4 {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter postfix expression: ");
    String post = input.nextLine();

    EvalPostfix ev = new EvalPostfix(post);
    int result = ev.eval();

}

} 

【问题讨论】:

    标签: java stack postfix-notation evaluator


    【解决方案1】:

    您需要向 MyStack 类添加验证以避免错误流。例如,如果 Stack 已满,请不要尝试将项目添加到 Stack inside push() 方法。此外,在执行 pop 或 peek() 操作之前,您必须检查 Stack 是否为空。看看下面的 pop() 操作中的验证。

    public E pop() {
    
        if(isEmpty()){
            // Handle the empty stack here (i.e : throw EmptyStackException)
        }
        top--;
        return data[top + 1];
    }
    

    【讨论】:

    • 好的,所以我实现了 push、peek、pop 方法的异常,但现在它只是在 pop 方法中抛出了 emptystackexception。我不确定从那里去哪里,因为在 EvalPostfix 中调用 pop 方法之前,其他方法似乎都很好。
    • 你传递给程序的输入是什么?
    • 我只是通过一个真正简单的“32+”来测试它是否工作,但这可能是问题所在。我也试过在中间有空格,也没有运气。
    猜你喜欢
    • 2021-06-27
    • 2011-10-14
    • 2014-08-13
    • 2020-12-18
    • 2014-10-07
    • 2014-09-10
    • 2021-01-25
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多