Postfix Expression Evaluator, pop method errors

233 views Asked by At

I'm trying to take an expression from the user and evaluate it but I keep getting pop method errors that are leading to arrayindexoutofboundsexceptions and null pointer exceptions. How do I fix this, and is there a problem that lies elsewhere that I'm missing? Thank you

Here is my stack class

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;
}
}

Here is the evaluator class

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();
}
}

and here is the main class

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();

}

} 
1

There are 1 answers

3
Rans On

You will need to add validations to your MyStack class to avoid error flows. For example, if the Stack is already full don't try to add the item to the Stack inside push() method. Also, you will have to check whether the Stack is empty, before doing the pop or peek() operation. Have a look at the validation inside the pop() operation below.

public E pop() {

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