programmer 20
programmer 20

Reputation: 59

Java Postfix Calculator Error

I am using a stack to create a postfix calculator in java. I have got the main part written however I am coming across some problems. For starters, I have to account for whitespace, and I am not sure how to do that with my current set up. I am not sure if that will totally fix the program, but it would be a start. Any help would be greatly appreciated.

 import java.util.Scanner;
 import java.util.Stack;
 public class Postfix 
{
public static void main(String[]args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a Postfix expression");
    String input = sc.nextLine();
    Stack<Integer> Pstack = new Stack<Integer>();
    int result = 0;
    for(int i=0; i<input.length();i++)
    {
        char ch = input.charAt(i);

        if(ch>='0' && ch<='9')
        {
            Pstack.push((int)(ch-'0'));
        }
        else
        {
            int o1 = Pstack.pop();
            int o2 = Pstack.pop();

            switch(ch)
            {
            case '+':result=o1+o2;
            break;
            case '-':result=o1-o2;
            break;
            case '/':result=o1/o2;
            break;
            case '*':result=o1*o2;
            }
        }
        Pstack.push(result);
    }
    result = Pstack.pop();
    System.out.println("result: "+ result);
   }
}

Upvotes: 1

Views: 889

Answers (1)

Gernot
Gernot

Reputation: 384

As mentioned in the comments, put

if(ch == ' ') continue; 

directly after

char ch = input.charAt(i);

This will fix the issue with the whitespace.

Another issue is that

Pstack.push(result);

is executed every time, not just in case an operator has been evaluated.

So this statement should be the last one within the "else" case.

You also have to correct the way how the arguments are popped from the stack.

e.g. if you have the postfix expression 12- (which should evaluate to -1), 2 is on top of the stack and 1 comes after. In the current solution the result would be 2 -1 as the arguments are retrieved in the wrong order.

So

int o1 = Pstack.pop();
int o2 = Pstack.pop();

should be corrected to

int o2 = Pstack.pop();
int o1 = Pstack.pop();

Upvotes: 2

Related Questions