Java:BufferedReader和NullPointerException

时间:2012-09-28 20:04:01

标签: java nullpointerexception bufferedreader

我的代码按照假设运行,当我输入if语句时出现问题:

if (sList.get(i).equals(null)){break;}

程序崩溃时出现以下调试信息(NullPointerException):

  

显示java.lang.NullPointerException       在HangmanLexicon。(HangmanLexicon.java:51)       at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)       at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)       at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)       at java.lang.reflect.Constructor.newInstance(Constructor.java:513)       在java.lang.Class.newInstance0(Class.java:355)       在java.lang.Class.newInstance(Class.java:308)       在sun.applet.AppletPanel.createApplet(AppletPanel.java:807)       在sun.applet.AppletPanel.runLoader(AppletPanel.java:714)       在sun.applet.AppletPanel.run(AppletPanel.java:368)       在java.lang.Thread.run(Thread.java:680)

以下是所有代码(是的,我知道它很混乱,在学习新东西时看起来那样):

public HangmanLexicon() 
{
/* 1. Open the data file HangmanLexicon.txt using a 
 * BufferedReader that will allow you to read it line by line. */
String readWord = "";


 try
 {
 BufferedReader rd = new BufferedReader (new FileReader ("ShorterLexicon.txt"));

    while (true)
    {
        readWord = rd.readLine();
        println(readWord);
        sList.add(readWord);
        if (readWord == null){
            println("Shit has hit the fan.");
            break;}
    }
    rd.close();
 }
 catch (IOException ex)
 {
     println ("Shit has hit the fan.");
     throw new ErrorException(ex);
 }

 println("readWord: "+ readWord);
/* 2. Read the lines from the file into an ArrayList. */
 for (int i = 0; i < sList.size(); i++)
    {
        if (sList.get(i).equals (null)){println("done.");}
        println("get: "+sList.get(i) + " pos: " + i);
    }

}

4 个答案:

答案 0 :(得分:4)

不要以这种方式测试null,而是使用:

if (sList.get(i) == null)

您对equals的使用存在一个问题,即如果NullPointerException的结果为get,则null会自然发生:因为您无法调用方法在null

答案 1 :(得分:4)

似乎sList.get(i)null,您在equals()上调用null操作,结果为NullPointerException

使用

if (sList.get(i)== null)

而不是

if (sList.get(i).equals (null))

答案 2 :(得分:2)

如果数组中有null值,则无法调用equal函数,只需与null进行比较

if(sList.get(i) == null){
    println("done.");
}else{
    println("get: "+sList.get(i) + " pos: " + i);
}

我建议你在ready循环中使用BufferedReader课程的while函数

while(rd.ready()){
   // read 
} 

请参阅ready()

答案 3 :(得分:0)

bufferedReader将String的值存储为&#34; null&#34;如果br.readLine()为空,则不为null

所以尝试检查

(!Stringval.equalisIgnoreCase("null"))

而不是

(Stringval != null) or (Stringval.equalsIgnoreCase(null))