-2

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.

It returns:

Man = (bread, meat, cheese)

Here's the exception:

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)
Sam
  • 900
  • 10
  • 18

1 Answers1

3

It sounds like you are actually shadowing the class member man with a local variable man. At your initialization

Man[] man = new Man[1];

This declares a new variable. Local variables with the same name as class members are allowed, and they will hide (aka shadow) the class level variable. So, while it looks like you are initializing man, you are in fact initializing a local array and not touching the one in your class. To just initialize it and not declare a new one, you want to say just:

man = new Man[1];
FatalError
  • 52,695
  • 14
  • 99
  • 116