0
votes

My code works as supposed, the a problem arises when I type in this if statement:

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

the program crashes with the following debug information (NullPointerException):

java.lang.NullPointerException at 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) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at sun.applet.AppletPanel.createApplet(AppletPanel.java:807) at sun.applet.AppletPanel.runLoader(AppletPanel.java:714) at sun.applet.AppletPanel.run(AppletPanel.java:368) at java.lang.Thread.run(Thread.java:680)

Here is all the code (yeah I know it´s messy, it looks that way when learning new stuff):

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

4 Answers

4
votes

It seems sList.get(i) is null and you are calling equals() operation on null which results in NullPointerException.

Use

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

instead of

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

Don't test for null this way, instead use:

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

Your usage of equals has a problem in that a NullPointerException will naturally occur if the result of the get is null: because you can't call a method on null.

2
votes

when you have a null value in your array, you can not call equal function, simply compare with null

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

i suggesting you to use function ready of class BufferedReader in while loop

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

see ready()

0
votes

The bufferedReader store the value of String as "null" and not null if br.readLine() is empty

So try checking

(!Stringval.equalisIgnoreCase("null"))

instead of

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