• Post Reply Bookmark Topic Watch Topic
  • New Topic

Variable Names when using an array  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am used to having variable names such as player1, player2, etc..., but how do I do this if I don't know the number of players? (It's determined via user input.) My sort-of solution was to have the user input the number of players and then to create an array of that length. The user then inputs the name of the n players and they become elements in the array via a loop executed n-times. My problem now is manipulating the elements. For example, if I want to give each player an amount of money that changes throughout the game, I don't really have the players as objects to manipulate. Can I use dot-operators on player[0], player[1], etc...?

 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume Player is an object. If so, then yes, you can use the . operator on any reference to an instance. When using an array of Player named players, players[n] references the instance at that index.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
P.S. It occurs to me that you'd be better off with a List implementation rather than an array.
 
Michael McGuire
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll look into Lists - thank you.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

You can read about Lists and related collections in the Java Tutorials. To expand on what Bear said earlier: myArray[123].foo(234) will work, if you make some sweeping assumptions!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!