i have this code.

numberPlayers = 2;
      players = new Player[numberPlayers];
      setName();
      setHand();

    private static void setName() {
        for(int i=0;i<numberPlayers;i++) {
            out.print("Player "+ i + " name: ");
            players[i].setName(in.nextLine());
            out.println();
        }
    }

    private static void setHand() {
        for(int i=0;i<numberPlayers;i++) {
            out.print("Player "+ i+1 + " hand: ");
            players[i].setName(in.nextLine());
            out.println();
        }
    }

but this gives me error:

ROCK-PAPER-SCISSORS GAME
NOTE: hand input will loop until user(s) input(s) valid hand values
VALID HANDS: R-Rock, P-Paper, S-Scissors

Select your option below:

[1] Player vs Player
[2] Player vs Computer 1
Exception in thread "main" java.lang.NullPointerException
at RPS2.Game.setName(Game.java:61)
at RPS2.Game.main(Game.java:37)
Player 0 name: Java Result: 1

what's wrong? i want to instantiate an array object named Player with two elements.

Initiating an array simply creates "holding spaces" for the elements. Each of those elements is, however, currently "null". If you expect to have a "Player" predefined at every element, then you need to loop over the array and create one in each spot. i.e.

String[] array = new String[5];
for (int i = 0; i < array.length; i++) {
  array[i] = "";
}

Edit: The default values for the array elements are as follows:

boolean[] --> false
int[], short[], float[], double[], long[], char[], byte[] --> 0
Object[] --> null

Edited 7 Years Ago by masijade: n/a

This article has been dead for over six months. Start a new discussion instead.