0

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)
4
  • 2
    Which variable is not initialized when you get to the line in question? Use a debugger and set a breakpoint nearby, and step through to determine the answer. Commented Mar 2, 2013 at 4:40
  • 1
    docs.oracle.com/javase/7/docs/api/java/lang/… Commented Mar 2, 2013 at 4:41
  • It is hard to give an answer with limited information, can you provide the initialization of the variables used? Commented Mar 2, 2013 at 4:44
  • 1
    Please post the full code and the error stack trace. Commented Mar 2, 2013 at 4:47

2 Answers 2

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];
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Could you please show me those mans? One is in method and other one that is initialized as man[i] = new Man()? How can I point to one correct man?
private Man[] man; is instance variable hidden by local variable Man[] man = new Man[1]; the man you are accessing in getMan(int) is not initialized.

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.