Converting infix to postfix and getting an EmptyStackException

127 Views Asked by At

I am working on a project to convert infix notation to postfix notation and then evaluate the equation. I established the precedence for each operator. When I use the ConvertToPostfix method I get the Exception. I understand the concept of the reverse polish notation calculator and I am just struggling with doing it with my code. I am new to stack overflow so if there is something that may seem a little confusing just let me know and ill try to edit it.

import java.util.Stack;
public class RPNCalctest {

public static void main( String[] args) throws  InvalidInfixEquationException {
    String example= "3+4/3*2"; //postfix notation would be 3 4 3 / 2 * +

    System.out.println(ConvertToPostfix(example));
    // TODO
}
//establish precedence
static int precedence(String c){
    switch(c){
        case"+":
        case"-":
            return 1;
        case"*":
        case"/":
            return 2;

        case")":
            return 3;
        case"(":
            return 4;
        default:
            return -1;
    }
}

// Precondition: every operator/operand will be separated by at least one space
public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException {
    
    String[] tokens = infix.split(" ");
    String result = "";
    Stack<String> stack = new Stack<>();
    for (int i = 0; i < tokens.length; i++) {
        String current = tokens[i];

        if (precedence(current) > 0) {

            while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(current)) {
                result += stack.pop() + " ";
            }
            stack.push(current);
        } else {
            result += current + " ";
        }
    }

    for (int i = 0; i <= stack.size(); i++) {
        result += stack.pop();
    }
    return result;
}

}

Exception in thread "main" java.util.EmptyStackException
at java.base/java.util.Stack.peek(Stack.java:101)
at java.base/java.util.Stack.pop(Stack.java:83)
at RPNCalctest.ConvertToPostfix(RPNCalctest.java:50)
at RPNCalctest.main(RPNCalctest.java:7)
1

There are 1 best solutions below

0
On

Your problem is here. You pop off one more entry than there is.

for (int i = 0; i <= stack.size(); i++) {
    result += stack.pop();
}

Consider size=2. You execute the loop for i=0, 1, 2.

I assume that the 'pop' line is line 53 as indicated in the stack trace, so for future reference, that's useful debugging info and you should use it.

It might be clearer if that loop were coded:

 while (!stack.isEmpty()) {
      result += stack.pop();
 }

No need for the extraneous variable 'i'.