Home > Software design >  Is there a way to change the names for each object created in a loop?
Is there a way to change the names for each object created in a loop?

Time:09-22

I am trying to create a for loop that creates a new object for each player in a game. Is there any way to make it so the name of the object (where I have written "player[i]" to be different for each iteration of the loop? Edit: What I want to do, more specifically, is make it so the first time the loop runs, the player that is created is called player1, the second time, player2, and so on.

for (int i = 0; i < playerNumber; i  ) {
            System.out.println("PLAYER "   (i 1)   "'S NAME IS:");
            String playerName = scan.nextLine();
            String p = "player"   (i 1);
            //Player player = new Player(playerName);
        }

CodePudding user response:

You want something like: Player [firstPlayerName] = new Player(playerName);? That's simply not possible afaik.

CodePudding user response:

You might want to use a map, but your player names have to be unique for that:

Map<String, Player> players = new HashMap<>();
for (int i = 0; i < playerNumber; i  ) {
  System.out.println("PLAYER "   (i 1)   "'S NAME IS:");
  String playerName = scan.nextLine();
  String p = "player"   (i 1);
  Player player = new Player(playerName);
  players.put(playerName, player);
}

Now you can access your players with players.get("Sam") if one of the players names is Sam. Of course you could also use your String p instead of the playerName when you put the player objects into the map.

But if you just want to access the players by their index, I would recommend a List<Player>:

List<Player> players = new ArrayList<>();
for (int i = 0; i < playerNumber; i  ) {
  System.out.println("PLAYER "   (i 1)   "'S NAME IS:");
  String playerName = scan.nextLine();
  Player player = new Player(playerName);
  players.add(player);
}

Here you can use the index (add puts it to the end of the list, so you don't have to specify i in the parameter list.): players.get(17) to get the player object at the 18th place in the list.

Not that you can't have an arbitrary start index, it always starts at 0. You have to do some calculation if you have a 1-based variable with the index.

I would recommend List over array for various reasons, e.g. that the length is not fixed, you can add and remove easily in a list, you can create a list without knowing the final length in advance, and you can use a list with other generics, while you cannot use arrays as types in generics.

  • Related