使用等于方法的否定

Chr*_*ker -2 java equals nullpointerexception while-loop

我正在尝试设置while循环,如下所示:

while(!data.equals("String");
Run Code Online (Sandbox Code Playgroud)

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

如果我将代码更改为:

while(data.equals("String");
Run Code Online (Sandbox Code Playgroud)

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

编辑:在评论员的要求下添加真实代码.

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

    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;
}
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加堆栈跟踪

 at Calculator.infixConvert(Calculator.java:57) 
 at Test.main(Test.java:7)
Run Code Online (Sandbox Code Playgroud)

don*_*uxx 6

你可以做到"Yoda风格":

while(!"String".equals(data)) {
     //writing code here you must!
}
Run Code Online (Sandbox Code Playgroud)

因为对于这种情况data是null然后它不会导致NPE,因为你调用"字符串"的equals方法

  • `;`没必要. (2认同)