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.