简体   繁体   中英

Postfix Evaluator unable to push value

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 declare the stack at class level, and peek it, not pop it, to get the final result. Your calculator also needs a C(lear) button to empty the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM