简体   繁体   中英

Java - Null Pointer Exception on String array

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");
}   

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM