使用等于方法的否定

时间:2014-02-23 22:56:21

标签: java while-loop nullpointerexception equals

我正在尝试按如下方式设置while循环:

while(!data.equals("String");

每当我运行此代码时,我都会收到NullPointerException。 这是为什么?

如果我将代码更改为:

while(data.equals("String");

我没有这样的例外,所以数据中必须有数据,对吗?

编辑:根据评论员的要求添加真实代码。

以下代码是尝试将中缀表示法转换为后缀表示法的方法。

    public static Queue infixConvert (LinkedListTest infix){
    Stack stack = new Stack();
    Queue postfix = new Queue();

    while(infix.head.data != "EOF"){

        if(isNumber(infix.head.data)){
            postfix.insert(infix.head.data);
            System.out.println("Insert Queue");
            System.out.println("Operator");
        }

        else if (infix.head.data.equals("(") || infix.head.data.equals(")")){
            if(("(").equals(infix.head.data)){
                stack.push(infix.head.data);
                System.out.println("Open paren");
            }
            else {
                infix.delete(")");
                while(!"(".equals(stack.head.data)){
                    stack.delete(")");
                    postfix.insert(stack.pop());
                    System.out.println("Insert Queue");
                }
                stack.delete("(");
                System.out.println("Close Paren");
            }
        }

        else{
            if(!(highPrec(stack.head.data, infix.head.data))){
                stack.push(infix.head.data);
                System.out.println("Push onto Lesser Operand");
            }

            else if(highPrec(stack.head.data, infix.head.data)){
                while(stack.head.data != null){
                    if (stack.head.data != "("){
                        postfix.insert(stack.pop());
                    }
                    else break;
                }
                stack.push(infix.head.data);
                System.out.println("Push onto Greater Operand");
            }

            if (infix.head.data == "EOL"){
                while(stack.head.data != "EOL"){
                postfix.insert(stack.pop());
                System.out.println("End Line");
                }
            }
        }
        System.out.println(infix.head.data);
        infix.head = infix.head.next;
        System.out.println("loop\n");
    }
    return postfix;
}
}

编辑:添加了堆栈跟踪

 at Calculator.infixConvert(Calculator.java:57) 
 at Test.main(Test.java:7)

2 个答案:

答案 0 :(得分:5)

你可以 "Yoda-style"

while(!"String".equals(data)) {
     //writing code here you must!
}

因为data的情况为null,所以它不会导致NPE,因为你调用了“String”的equals方法

答案 1 :(得分:1)

我已经解决了这个问题。

还有一些其他无意的行为导致“(”String从堆栈中删除,所以当while循环运行时,它会遍历整个堆栈,直到它达到null,并为我提供了一个NPE。

相关问题