How to return an array object without NullPointerE

2019-09-15 04:19发布

问题:

Declared:

private Man[] man;  

This is the initialization:

Man[] man = new Man[1];

    for (int i = 0; i < 1; i++){
        man[i] = new Man();
            for (int j = 0; j < 3; j++){
                man[i].eatThis(table.foods[table.topFood-1]);
                table.topFood--;
            }
    }

Want to print this:

System.out.println(getMan(0));

which goes to:

public Man getMan(int k){
 return man[k];
}

but I receive NullPointerException. Why? While:

System.out.println(man[0]);

works just fine.

Exception in thread "main" java.lang.NullPointerException
at ManRunning.getMan(ManRunning.java:80)
at ManRunning.newGame(ManRunning.java:133)
at ManRunning.<init>(ManRunning.java:57)
at RunDevilRun.main(RunDevilRun.java:9)

回答1:

the line (1)

Man[] man = new Man[1];

is hiding the instance variable declared in this line (2)

private Man[] man;

any decent IDE would show a warning for this.

here is how you should initialize the array man in the line (1) declared with line (2)

man = new Man[1];


回答2:

Obivously you have two man array variables, one that is initialized and one (a member variable) that isn't.