Exception in thread & ldquo; hand & rdquo; java.lang.NullPointerException during file playback

advertisements
Exception in thread "main" java.lang.NullPointerException
    at Library.loadBooks(Library.java:179)
    at UseLibrary.main(UseLibrary.java:105)

This error makes me crazy!

public void loadBooks(String s) throws IOException{
    String str[] = new String[6];
    String inFName = ".//" + s ;
    BufferedReader input = new BufferedReader(new FileReader(inFName));
    int x;
    double y;
    String line = "";
    while(line != null){

        for(int i=0; i<6; i++){
            str[i] = new String();
            line = input.readLine();
            str = line.split("[-]");
            x = Integer.parseInt(str[1]);
            y = Double.parseDouble(str[2]);
            Book a = new Book(str[0], x, y, str[3], str[4], str[5]);
            add(a);
        } 

    }
}

What's the problem with this code?

I initialize the array, but it didn't run!

Update 1

In save.txt I have is

1 Don Knuth-290-23.45-The Art of Programming with Java-HG456-Engineering-5
2 A. Camp-400-13.45-An Open Life-HSA234-Philosophy-1
3 James Jones-140-12.11-Oh, Java Yeah!-SDF213-Science Fiction-2
4 J. Campbell-250-32.45-An Open Life-JH45-Science-3
5 Mary Kennedy-230-56.32-Intro to CS Using Java as the Language-USN123-Science-4


The problem I think is

You have 5 or less lines in your saved.txt and because of for loop for the 6th iteration as there is no data for line, you are getting NullPointerException.

Please follow below step and let me know what you get...

Instead of

while(line != null){

    for(int i=0; i<6; i++){
        str[i] = new String();
        line = input.readLine();
        str = line.split("[-]");
        x = Integer.parseInt(str[1]);
        y = Double.parseDouble(str[2]);
        Book a = new Book(str[0], x, y, str[3], str[4], str[5]);
        add(a);
    } 

}

Use

while ((line = input.readLine()) != null) {
        str = line.split("[-]");
        Book a = new Book(str[0], Integer.parseInt(str[1]), Double.parseDouble(str[2]), str[3], str[4], str[5]);
        add(a);
}

Let me know if you still get any problem.

Update 1

Per your update,

In save.txt I have is

1 Don Knuth-290-23.45-The Art of Programming with Java-HG456-Engineering-5
2 A. Camp-400-13.45-An Open Life-HSA234-Philosophy-1
3 James Jones-140-12.11-Oh, Java Yeah!-SDF213-Science Fiction-2
4 J. Campbell-250-32.45-An Open Life-JH45-Science-3
5 Mary Kennedy-230-56.32-Intro to CS Using Java as the Language-USN123-Science-4

As you see there are 5 lines in your file, for 6th iteration you are getting NullPointerException.

Also read, how to print content of files in Java.