2

I am attempting to assign a value to an array object like this:

public class Players {
    String Name;
}

Players[] player = new Players[10];
String name = Mike;
player[1].Name = name;

I am getting a NullPointerException and am not sure why. What could be causing this?

2
  • 5
    This class should really be named Player, since each instance is only one player.. Commented May 14, 2012 at 3:04
  • Thanks for the suggestion. I think will change the class to player and the array to players Commented May 14, 2012 at 3:11

2 Answers 2

9

This is because creating a new array does not create individual objects inside the array; you should be creating them separately, e.g. in a loop.

Players[] player = new Players[10];
for (int i = 0 ; i != player.length ; i++) {
    player[i] = new Players();
}
Sign up to request clarification or add additional context in comments.

2 Comments

I understand what you are saying in concept but not implementation. Could you please give an example?
Wow thank you. I didn't realize the objects were not created by initializing the array
4

new Players[10] makes an array with 10 slots. It doesn't put anything in the slots. So all 10 elements of the array are null.

You need to create the objects and stick them into the array. For example:

for (int i = 0; i < player.length; i++) {
    player[i] = new Players();
}

Comments

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.