views:

69

answers:

1

I'm reading lines from a file, and I believe that once I've read all the lines, I get an exception because of my while loop condition.

Exception in thread "main" java.lang.NullPointerException
    at liarliar.main(liarliar.java:79)

... the code...

// read the first line of the file
iNumMembers = Integer.parseInt(br.readLine().trim()); 

// read file
while ((sLine = br.readLine().trim()) != null) {

    // extract the name and value 'm'
    String[] split = sLine.split("\\s+");
    sAccuser = split[0];
    iM = Integer.parseInt(split[1]);
    saTheAccused = new String[iM];

    for (int i = 0; i < iM; i++) {
        saTheAccused[i] = br.readLine().trim();
    }

    // create member
    // initialize name and number of members being accused
    Member member = new Member();
    member.setName(sAccuser);
    member.setM(iM);
    member.setAccused(saTheAccused);

    veteranMembers.add(member);
}

The for loop inside will have to read several lines so if the last line of the file is read, then the while will try to readLine() and that will fail because the whole file has been read. So how does the BufferedReader readLine() work and how can I safely exit my while loop?

Thanks.

+2  A: 

readLine() returns null on EOF, and you are trying to call trim() on a null reference. Move the call to trim() inside the loop, as in

// read file
while ((sLine = br.readLine()) != null) {

    // extract the name and value 'm'
    String[] split = sLine.trim().split("\\s+");
Jim Garrison
Actually I just realized that I'm using the regex to ignore whitespace... so the trim() is useless right?
Hristo
No, if the input has leading blanks the result array will contain an empty string as the first element (index [0]). If you don't want this behavior, you must still trim(). If this seems illogical, consider what you would want if the delimiter was a comma and you were splitting the string ",a,b,c". In that case you would probably want to know that the first "field" was empty.
Jim Garrison
You're right... I do want trim. Thanks!
Hristo