简体   繁体   English

Postfix评估程序无法推动价值

[英]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. 因此,我收到了NullPointerException错误。 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. 您的计算器还需要一个C(清除)按钮来清空堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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