Search code examples
javacalculatorrpn

RPN PostFix Calculator output not as expected for simple arithmetic


I have written a class to do post fix calculations on the basic arithmetic operators - the code is below.

public class PostFixCalculatorRPN
{
    public static void main()
    {
        String input = JOptionPane.showInputDialog("PostFix expression: ");
        Stack s = new Stack();

        for (int i = 0; i < input.length(); i++)
        {
            char ch = input.charAt(i);
            if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
            {
                // pop 2 numbers off and operate
                switch (ch)
                {
                case '+':// push the sum of the 2 numbers back on stack
                case '-': // push the difference of the 2 numbers back on stack
                case '*': // push the product of the 2 numbers back on stack    
                case '/':// push the quotient of the 2 numbers back on stack
                }
            } else
                s.push(ch + "");
        }
        int answer = Integer.parseInt((String) s.pop());

        System.out.println(printInput(input) + ": Evaluates to -> " + answer);
        System.exit(0);
    }

    public static String printInput(String s)
    {
        String str = "";

        for (int i = 0; i < s.length(); i++)
            str += s.charAt(i);

        return str;
    }
}

I believe that the Stack class I have with this works correctly, but I can post that as well if necessary.

The output of my calculator is not as expected, for example an input of 53+ evaluates to 3 and 92* evaluates to 2, whereas I was expecting 8 and 18 respectively.


Solution

  • Everything you have is really close but without code in your case statements it will simply return the last non-operator in your input string (last item pushed onto stack). Do you understand completely the code you have and what a stack is? You are stepping left to right through the input and pushing numbers onto the stack until you hit an operator (+-*/) and then applying the operator to those numbers you conveniently pushed on the stack. These numbers pop off in reverse order that you pushed them on. You should just need to pop two numbers off the stack and then perform the desired operation and push the result. Something like (reusing pieces already in your code):

    s.push(Integer.parseInt((String)s.pop()) + Integer.parseInt((String)s.pop()) + "");
    

    One of the operators will be slightly trickier due to ordering of the pops. Just think about it.