[英]Postfix Evaluator unable to push value
我有一个类的分配-使用堆栈和队列的后缀评估器。 元素在进入评估方法的队列中,并且应该使用堆栈来存储元素。 但是,由于某种原因,我无法将最终值压入堆栈。 方法如下:
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;
}
如果我使用,我可以得到正确的答案
final_value=t;
但是问题在于,由于最终值不在堆栈中,因此继续使用计算器将无法对其进行任何进一步的输入。 因此,我收到了NullPointerException错误。 为此的测试临时解决方案是使用以下代码忽略空堆栈错误:
if(!nums.isEmpty()){
a1=Integer.parseInt(nums.pop().data);
}
我非常感谢对此错误的任何解释。
您需要在类级别声明堆栈,并查看而不是弹出它,以获得最终结果。 您的计算器还需要一个C(清除)按钮来清空堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.