943,701 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 580
  • Java RSS
Sep 5th, 2009
0

instantiating array objects

Expand Post »
i have this code.

java Syntax (Toggle Plain Text)
  1. numberPlayers = 2;
  2. players = new Player[numberPlayers];
  3. setName();
  4. setHand();
  5.  
  6. private static void setName() {
  7. for(int i=0;i<numberPlayers;i++) {
  8. out.print("Player "+ i + " name: ");
  9. players[i].setName(in.nextLine());
  10. out.println();
  11. }
  12. }
  13.  
  14. private static void setHand() {
  15. for(int i=0;i<numberPlayers;i++) {
  16. out.print("Player "+ i+1 + " hand: ");
  17. players[i].setName(in.nextLine());
  18. out.println();
  19. }
  20. }

but this gives me error:
Quote ...
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.
Similar Threads
Reputation Points: 11
Solved Threads: 0
Junior Poster in Training
scias23 is offline Offline
69 posts
since Jan 2009
Sep 5th, 2009
0

Re: instantiating array objects

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.

Java Syntax (Toggle Plain Text)
  1. String[] array = new String[5];
  2. for (int i = 0; i < array.length; i++) {
  3. array[i] = "";
  4. }

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

Java Syntax (Toggle Plain Text)
  1. boolean[] --> false
  2. int[], short[], float[], double[], long[], char[], byte[] --> 0
  3. Object[] --> null
Last edited by masijade; Sep 5th, 2009 at 4:15 am.
Moderator
Reputation Points: 1471
Solved Threads: 490
Industrious Poster
masijade is offline Offline
4,043 posts
since Feb 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: plz help.
Next Thread in Java Forum Timeline: Java Encryption and Decryption





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC