0

This is the code I working on. It's inside a method and the idea is for it to open a file and check the contents, or the lack of, and report back.

However I'm getting a NullPointerException on the line that I pointed to below.

I have no idea how to fix this. I tried debugging which shows that at the time the line is run the 1st element of the String[] contains text, so that's not a problem.

int i = 0;
int numChar=1, numLines;
String[] line = new String[1000];

try {
    BufferedReader in = new BufferedReader(new FileReader(file));
    try {
        while(numChar > 0) {
            //String[] line = new String[1000];
            line[i] = in.readLine();
PROBLEM-->  numChar = line[1].length();
            i++;
        }            
    } catch (EOFException ex) {
        JOptionPane.showMessageDialog( null, "Error" );
        //break;
    }      
}
catch(IOException e) {
    JOptionPane.showMessageDialog( null, "Missing file or no data to read." );
    System.out.println("IO Error - Missing file");
}   
0

1 Answer 1

2

I suspect you just need to change the array access index to use i instead of 1.

numChar = line[i].length();

And you should also check for null as the BufferedReader will return (from the docs):

null if the end of the stream has been reached

numChar = line[i] == null ? 0 : line[i].length;

You might want to expand that so you break out of your loop instead of assigning a length of null.

String s = in.readLine();
if (s == null) {
  break;
}
else {
  line[i] = s;
  numChar = line[i++].length();
}

EDIT in response to comments.

At risk of confusing the issue, my preference would be to rewrite your loop. You don't seem to need numChars outside the loop, so I would remove it so as to reduce your method scope's variables. I also suspect you don't want to stop reading on empty lines, just at the end of the stream:

while (true) { // for(;;) if you prefer
    String s = in.readLine();
    //if (s == null || s.length() == 0) break; // stop on empty lines and end of stream
    if (s == null) break; // stop at end of stream only
    line[i++] = s;
}
Sign up to request clarification or add additional context in comments.

4 Comments

That's my bad, it used to be an 'i' but I changed it to '1' while trying to debug, it gives same error when it's i
@user2627736. Yes, you'll need to do a null check as well - see my edit with the documentation reference.
Imho it will be more efficient to rewrite the loop condition instead of if else logic.
@RandomHuman. I don't disagree, but didn't want to rewrite the OP' s entire program and leave them trying to work out what had been done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.