0

I am pretty new to java and I am trying to write a simple game but I am getting this error in my program "java.lang.NullPointerException" couldn't figured out why I am getting this so I am posting my code here.

    public static void main(String[] args) {
       Scanner console = new Scanner(System.in);
       System.out.println("How many players?:");
       int t = console.nextInt();
       Player p[] = new Player[t];
       for(int i=0; i<t; i++){
           System.out.println("Player " + i+1 + " enter your name:");
           p[i].player_name = console.nextLine();
           System.out.println(p[i].player_name + " Easy(1), Medium(2), Hard(3), enter one integer");
           p[i].number = console.nextInt();
           System.out.println("Player " + i+1 + "name: " + p[i].player_name + "your integer is " + p[i].number);
      }
   }

And this is my Player class

public class Player {
   public String player_name;
   public int number;

   public Player() {
       this.player_name = " ";
       this.number = 0;
   }
}
1
  • at the beginning of your loop you need to add p[i] = new Player(); Commented Mar 21, 2014 at 20:15

5 Answers 5

4

Array elements of Object types are null by default. Create an instance of Player before attempting to assign its fields

for (int i=0; i<t; i++) {
   p[i] = new Player();
   ...
}   
Sign up to request clarification or add additional context in comments.

Comments

2

You need to initialize your p[i] first. You can put this at the start of the for-loop inside the loop:

p[i] = new Player();

Comments

0

Here you make an array of players but you dont fill it with a player

Player p[] = new Player[t];

do this in you loop first

p[i] = new Player(); 

Comments

0

The only thing that this statement does

Player p[] = new Player[t];

is just allocating memory for t references to the Player objects. It does not initialize any Player object, so these references referes to null objects, therefore when you invoke

p[i].player_name    

you get the NullPointerException.

Comments

0

You are missing the instantiation of the new player objects inside the for loop. When you declare the array with: Player p[] = new Player[t];, you are just creating the array of type Player. Before assigning values inside the loop, instantiate an object in the proper position of the array. i.e:

for (int i = 0; i < t; i++) {
   p[i] = new Player();
}

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.