+ 2

how to assign a different key to unknown amount of values in array java?

how to assign a different key to unknown amount of values in array java? to be more clear, lets say we have unknown amount of players (int players = random number). and we also already have the same amount of names as the players (so we can assign player1 = names[0]). how can i do that the key (String key) will change for each name assigning? if this method would work i would do it like that: for (int j = 0; j < players; j++){ String Player[j] =names[j]; } how can i make it work?

3rd Aug 2020, 9:18 AM
Yahel
Yahel - avatar
9 Answers
+ 6
To keep it easier I used a name array: https://code.sololearn.com/c3lthpCMH24b/?ref=app
3rd Aug 2020, 2:05 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
Hello yahel Why so complicated? You get an integer n (input or random) for the amount of players. String[] player = new String[n]; Now you can add the names to each player in a for loop. Or if you really don't know the number of players, you can use an ArrayList. List<String> player = new ArrayList<>(); In both cases player1 is at index 0. playerN at n - 1.
3rd Aug 2020, 1:33 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
yahel From where do you get the names? User input or do you have a name array?
3rd Aug 2020, 1:54 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
For it can be used the ArrayList instead of an Array. https://www.sololearn.com/learn/Java/2179/
3rd Aug 2020, 10:50 AM
JaScript
JaScript - avatar
+ 3
yahel the code designed by Denise Roßberg shows you great both possibilitys. After completing the Java Tutorial you will be able to better handle the challenges. Enjoy coding.
3rd Aug 2020, 3:23 PM
JaScript
JaScript - avatar
+ 1
1. You cannot say String Player[j] cause Player is not an initiated array and if it would be you cant declare it as a String again. 2. Do you want a HashMap with value and key? 3. Why would you have a changing String as a key if you dont know what key would be usefull? Is it maybe a better idea to just have an array of Strings for the players?
3rd Aug 2020, 10:21 AM
Jnn
Jnn - avatar
+ 1
Jnn I have unknown amount of players. And I have the same amount of names as the amount of players. My goal is to assign each player to a name. HashMap won't work as I need it to work.
3rd Aug 2020, 10:42 AM
Yahel
Yahel - avatar
+ 1
Ja Play how would the code look?
3rd Aug 2020, 11:09 AM
Yahel
Yahel - avatar
+ 1
Can you show me how would it look?
3rd Aug 2020, 1:35 PM
Yahel
Yahel - avatar