循环空指针异常

Joh*_*now 0 java exception-handling nullpointerexception while-loop

如果newWordnull,它不应该进入循环,但为什么它进入循环并给出java.lang.NullPointerException

newWord = "abcd";
while(!newWord.equals(null))
{
    try {
    newWord = br.readLine();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    }
    catch(NullPointerException p)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

它给出了堆栈跟踪,但我没有在任何地方使用printStackTrace()

Wil*_*son 8

newWord本身是空的.当对象为null时,您无法调用其上的任何方法,因为未定义对象.作为.equals一种方法,您将获得一个例外.试试这个:

newWord != null
Run Code Online (Sandbox Code Playgroud)

这是调试器很容易解决的问题.学习使用调试器是令人沮丧的(正如学习任何新工具一样),但它可以为您节省数小时的痛苦.这是你的朋友.