【问题标题】:Postfix Calculator Java -cannot resolve or is not a fieldPostfix Calculator Java - 无法解析或不是字段
【发布时间】:2019-04-15 05:34:58
【问题描述】:

我在后缀计算器中遇到此错误:整数操作数无法解析或不是字段。下面我展示了主要代码,以及来自 IntegerOperand 类文件的代码。我怎样才能解决这个问题?我正在尝试从 IntegerOperand 类调用 add 函数。

public class IntegerOperand implements CalculatorOperand<IntegerOperand> {

    BigInteger value;

    IntegerOperand (BigInteger value) {
        this.value = value;
    }

    public IntegerOperand add (IntegerOperand that) {
        return new IntegerOperand(this.value.add(that.value));
    }
    public IntegerOperand subtract (IntegerOperand that) {
        return new IntegerOperand(this.value.subtract(that.value));
    }
    public IntegerOperand multiply (IntegerOperand that) {
        return new IntegerOperand(this.value.multiply(that.value));
    }

    public String toString () {
        return value.toString();
    }   
}


public void operation (OperationType operation) {

        T t1;
        T t2;
        if(stack.isEmpty())
        {   

              t2= stack.pop();
             t1= stack.pop();
            stack.push(t1.IntegerOperand.add(t2));

        }
    }

【问题讨论】:

    标签: java list stack


    【解决方案1】:

    主要问题是您没有正确调用该函数。

    // You don't need the class name
    //stack.push(t1.IntegerOperand.add(t2));
    stack.push(t1.add(t2));
    

    其次,检查堆栈是否为空,如果是,则尝试从中获取pop。但是您应该检查堆栈是否为空:if (!stack.isEmpty())。但是由于您随后对 pop 进行了 2 次调用,因此您应该检查堆栈中是否至少有 2 个项目。

    if (stack.size() >= 2) {   
        t2 = stack.pop();
        t1 = stack.pop();
        stack.push(t1.add(t2));
    }
    

    【讨论】:

    • 谢谢!但是,该函数必须允许堆栈中包含少于 2 个项目的堆栈,并且如果堆栈包含少于 2 个项目,则代码无法修改堆栈。在这种情况下我应该考虑什么?
    • @ChloePupaiboon 如果堆栈少于 2 项,此代码将不会修改堆栈。对于只有一个项目的堆栈,您可以添加 else 来处理这种情况。
    猜你喜欢
    • 2022-01-09
    • 2023-03-28
    • 2014-03-27
    • 2014-01-05
    • 2016-05-20
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多