[英]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.