3

I am looking to do what I explain below or something similar for a program that I'm writing. Prior to this part of my program I have an array that holds the names of players that are playing the game.

I am wanting to create a for loop that will initialize a new array based around the number of players that there are and name that new array the name of that player.

So you get a better idea:

for (int i = 0; i < nPlayers; i++) {
    String name = playerNames[i];
    int[] name = new int[nCategories];  
}

So you can see that I am attempting to assign a new array based off of the name of something I have stored in a different array. Is there any way to do this? Or something similar, which I suppose might be better/more efficient?

This is a Java program btw.

Thanks!

BlueBear
  • 7,469
  • 6
  • 32
  • 47

2 Answers2

3

There's not really a clean way to create a variable with a dynamic name like you're trying to do. Perhaps a good option would be to have a Map, and create a new key in the map for each player, with the player's name as the key, and the value as a new Int array.

Ian McMahon
  • 1,660
  • 11
  • 13
3

I want to start about by noting that Ian makes a valid point. If you want to be able to retrieve a variable dynamically using a String a map is a great candidate. Create a map that uses a String for the key and an int[] array as the value. Then you can call the int[] out of the map using your String key.

Map<String, int[]> players = new Map<String, int[]>();
String myname = "myname";
int[] myInts = {0,1,2};
players.put(myname, myInts);
int[] intArrayForPlayer = players.get(myname);

However, the main advantage of using Java is that it is an object oriented language. You may want to strongly consider using classes to achieve your goal. You can create a class called Players with class variables to hold all of the data you'll need for each Player. Then you can create Player myPlayer = new Player(); objects and use them to hold all your information.

You could use an array or ArrayList to hold all of your player objects.

Kyle
  • 14,036
  • 11
  • 46
  • 61