I am writing Java code for a Monopoly game and I am getting a NullPointerException on the line with the SetPlayerName(tempName, numPlayersCounter); method call. This method sets the name of a Player in a Player array. When the program is run, the console says that the value of numPlayersCounter is 1, the length of the Player array playersArr is 3.
sc2.ok1Button.addActionListener(new ActionListener() //middle ok button
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Name ok button pressed");
System.out.println("Name is:" + sc2.nameField.getText());
String tempName = sc2.nameField.getText();
System.out.println("numPlayersCounter value: " + numPlayersCounter);
SetPlayerName(tempName, numPlayersCounter);
System.out.println("Player " + numPlayersCounter + "name: " +playersArr[numPlayersCounter].GetName());
sc2.EnableName(false);
sc2.EnablePieces(true);
}
});
The method SetPlayerName is defined as:
public static void SetPlayerName(String n, int id)
{ playersArr[id].SetName(n); }
and playersArr is declared before the constructor and main as:
protected static Player [] playersArr; //player 0 is the bank
In Player.java, the name is set as an empty string in the constructor and the SetName method is defined as:
public void SetName(String n)
{ name = n; }
I have tried to set the name directly from the actionPerformed method and incrementing a different Player variable. The problem seems to be with accessing the correct array element, but it should be accessing element 1 of an array of length 3.
What do I need to do to fix this? Any help would be greatly appreciated.