Reputation: 31
I'm not sure what I am doing wrong here. I'm fairly new to Java programming.
My goal was to have 4 players enter their names and scores of a game, and then return the names and scores in descending order or scores.
I created a class, with a Player. And then made a dynamic variable to change how many objects I make.
I ask for the username, and then the score, but that's where I am getting stuck. The program compiles fine, but it tells me this. "What is the name of Player # 1?Exception in thread "main" java.lang.NullPointerException
at HelloWorld.main(HelloWorld.java:20)"
I'm not sure why I'm getting this error. Can anyone help me?
//Array
import java.util.*;
public class HelloWorld {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int allPlayers;
int index[] = new int[12];
int i;
System.out.print("Please enter the number of players");
allPlayers = input.nextInt();
Player[] playersArray = new Player[allPlayers];
for(i = 0; i <allPlayers; i++){
System.out.print("What is the name of Player # " + (i+1) +"?");
playersArray[i].name = input.nextLine();
System.out.print("What was the score of Player # " + (i+1) + "?");
playersArray[i].score = input.nextInt();
}
for(i = 0; i <allPlayers; i++){
for(int j = 0; j <allPlayers; j++){
if(index[i] < playersArray[j].score){
index[i] = playersArray[j].score;
}
}
}
for(i = 0; i <allPlayers; i++){
System.out.print(playersArray[index[i]].name);
System.out.print(playersArray[index[i]].score);
}
}
}
class Player {
int score; // players score
String name; // players name
}
Upvotes: 0
Views: 43
Reputation: 12391
You are declaring it but not assigning the memory to the object, that's why getting a NULL Pointer
exception. Right before assigning the values, create the object.
for(i = 0; i <allPlayers; i++){
playersArray[i] = new Player();
Upvotes: 0
Reputation: 393771
When you initialize an array of reference type :
Player[] playersArray = new Player[allPlayers];
all the elements of the array are initialized to null
.
You forgot to initialize playersArray[i]
.
Add
playersArray[i] = new Player();
before
playersArray[i].name = ...
Upvotes: 2