0

I have created a Player class that takes in String playerName to it's constructor. The game will have human players and computer bots, each is created as Player player1 = new Player("Tom");. After I have created each Player instance for the human players, I would now like to create a loop that achieves the following:

for (int i = (numHumanPlayers + 1); i < totalNumPlayers; i++) {
    String instanceName = "player" + i;
    String playerName = "Bot " + (i - numHumanPlayers);
    Player <instanceName> = new Player(playerName);
}

where <instanceName> is the contents of String instanceName.

For example, if there were two human players and two computer players, this would result in the following for players:

Player player1 = new Player("Tom");
Player player2 = new Player("Jerry");
Player player3 = new Player("Bot 1"); 
Player player4 = new Player("Bot 2");

I have seen the Class.forName() method as well as using the Constructor.newInstance() and I believe that these are what I need to use. However, I cannot figure out the syntax to use these methods in order to achieve the result for my custom Player class.

KOB
  • 4,084
  • 9
  • 44
  • 88
  • 1
    You can't do this; even if you could create a variable with a dynamic name, you wouldn't then be able to refer to it. You should really use an array (or a list) for this. – Andy Turner Feb 26 '16 at 10:35
  • 1
    you can use a map and make keys as playes1, player2 and so on .. – bob Feb 26 '16 at 10:36
  • @AndyTurner When the players are constructed, they are only given a name, but the `Player` class has other variables that will be initialised as the game goes on. So my only option is to create each computer player is to individually write the constructor for each one? This isn't a problem as of now, but I do not know, as my development of the game progresses, there may be a variable number of humans to computer players. – KOB Feb 26 '16 at 10:39
  • Writing a constructor has nothing to do with the variable to which it is assigned (if any; nothing stops you writing `new Player("Tom");` as a statement by itself). You just need a list/array/map which you declare outside the loop, and then add/assign/put values into it inside the loop. See the top answer on the dupe question. – Andy Turner Feb 26 '16 at 10:42
  • @p2. so inside my loop there would be something along the lines of `playerMap.put(instanceName, new Player(playerName);`? – KOB Feb 26 '16 at 10:42
  • @CornOnTheKob exactly. – Andy Turner Feb 26 '16 at 10:43
  • yes, for each key there will be a new player object in that map . – bob Feb 26 '16 at 10:44
  • Works perfectly, thank you – KOB Feb 26 '16 at 10:53

0 Answers0