方法中的私有类 - java

时间:2015-03-16 04:14:35

标签: java class

我试图编写一个程序,以明显的波兰形式(即6,3,')来输入代数表达式(即(6 * 3)+(7-2))。 *',7,2,' - ',' +'),通过将整数放在堆栈上并在前两个元素上调用操作数,然后最终返回任何& #39; s在堆栈顶部(希望在堆栈上只有一个元素 - 答案)。

我对java很新,所以我确信这是一个非常平凡的问题,但我似乎无法使用我的堆栈(名为&# 39;存储')可访问和可编辑的类中的其他方法。

我的堆栈实现似乎工作正常,如果它出现在火灾中,我会发布它#。

当函数必须调用其中一个操作数子函数(如add())时,我的问题就出现了。它似乎完全忘记了存储已存在并已被编辑,而是将其视为空堆栈。我试着扔掉这个'在前两个实例之外的所有事情面前,但这并没有做太多。如何获得共享'存储'的功能?贯穿其所有功能?

示例运行:

Eval myEval = new Eval;
myEval.evaluate(6, 3, '+', 4, 9, '*', '-'); 

Exception in thread "main" java.lang.NullPointerException
at Eval.add(Eval.java:45)
at Eval.evaluate(Eval.java:13)

public class Eval {
     public stack store;
     public Eval(){
        stack store = new stack();
    }

    public int evaluate(Object ... parts){
        for(Object part: parts){
            if(part instanceof Character){
                char operator = (Character) part;
                if(operator=='+'){
                    add();
                }
                else if(operator=='-'){
                    subtract();
                }
                else if(operator=='*'){
                    multiply();
                }
                else if(operator=='/'){
                    divide();
                }
                else{
                    throw new IllegalArgumentException("Illegal operand");
                }
            }
            else if(part instanceof Integer){
                int number = (Integer)part;
                store.push(part);
                System.out.println(store.peek());
            }
            else{
                throw new IllegalArgumentException("Expected char or int");
            }
        }
        if(store.peek()==null){
            throw new IndexOutOfBoundsException("No value to return");
        }
        return (int)store.pop();
    }
    private void add(){ 
        int x=(int)store.pop(); //error occurs on this line
        x+=(int)store.pop(); 
        store.push(x);
    }
    private void subtract(){
        int x=(int)store.pop();
        int y=(int)store.pop();
        x=y-x;
        store.push(x);
    }
    private void multiply(){
        int x=(int)store.pop();
        int y=(int)store.pop();
        x=y*x;
        store.push(x);
    }
    private void  divide(){
        int x=(int)store.pop();
        int y=(int)store.pop();
        int z = Math.floorDiv(x,y);
        store.push(z);
    }
}

2 个答案:

答案 0 :(得分:2)

看起来您的构造函数Eval()将一个新堆栈分配给名为“store”的临时变量,该变量不是Eval类的公共“store”变量。因此,当输入Add时,实例变量“store”为null。将Eval()的实现更改为:

public Eval(){
    this.store = new stack();
}

或者,在该方法中为store(getStore)创建一个getter方法并将其实例化(如果为null),但是,如果你这样做,你必须记住通过getStore()而不是直接引用它。

答案 1 :(得分:0)

当堆栈为空时,很可能会尝试弹出。此外,当您已经知道堆栈将包含int时,不必为x转换赋值。 int x =(int)store.pop(); 可以 int x = store.pop();

我建议为您的操作员功能添加支票,例如:

if(stack.getLength() > 0) {
    //then add operation
} else {
  //throw an error
}