Home Postfix Evaluator unable to push value
Reply: 0

Postfix Evaluator unable to push value

user1697
1#
user1697 Published in June 18, 2018, 3:34 am

I have this assignment for a class- a postfix evaluator using stacks and queues. The elements are in a queue entering the evaluation method, and a stack should be used to store elements; however, for some reason I cannot push the final value onto the stack. The method is below:

private String processPostfix(MyQueue postfix)
{
    postfix.viewQueue();
    MyQueue temp=postfix;
    MyStack nums=new MyStack();
    String t="";
    String final_value="";
    int a2;
    int a1 = 0;

    while(!temp.isEmpty()){
        t=(String)postfix.dequeue();
        if(t.equals("+") || t.equals("*") || t.equals("-")){
            a2=Integer.parseInt(nums.pop().data);
            a1=Integer.parseInt(nums.pop().data);
            if(t.equals("+")){
                t=Integer.toString(a1+a2);
            }
            else if(t.equals("*")){
                t=Integer.toString(a1*a2);
            }
            else if(t.equals("-")){
                t=Integer.toString(a1-a2);
            }
        }
        nums.push(new StackNode(t));
    }
    final_value=nums.pop().data;
    return final_value;
}

I can get the right answer to appear if I use

final_value=t;

But the problem is is that continuing to use the calculator, since the final value is not on the stack, any further input cannot be processed against it. I therefore get a NullPointerException error. The test temporary solution for this has been to ignore the empty stack error using this code:

if(!nums.isEmpty()){
    a1=Integer.parseInt(nums.pop().data);
}

I would really appreciate any explanation of this error.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309074 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO