Array NullPointerException? [duplicate]

2019-02-07 15:22发布

问题:

This question already has an answer here:

  • What is a NullPointerException, and how do I fix it? 12 answers

Ok. I don't get why my code is reporting a NullPointerException, but I've been here for quite a while trying to figure it out.

And no, files is not null.

Edit: That was a mistake on my part, it was null (I didn't see the order I was running the functions.

Here is my code:

public String[] files;

private void updateRefs(String filepath) {
    try { 
        scr++;
        files[scr] = filepath; //NullPointerException???
    } catch ( Exception e ) {
        e.printStackTrace();
    }
}

回答1:

You have to new it, otherwise it is null:

String[] files = new String[10]; //or whatever size you need