[英]How do I associate a string array with an int array
I am just new to coding and trying to write a basic program.我只是编码和尝试编写基本程序的新手。
I want to generate an array of random numbers(each under 50) and then associate these numbers with a string array(of names) that has been populated by the user.我想生成一个随机数数组(每个小于 50),然后将这些数字与用户填充的字符串数组(名称)相关联。
I need it to work so that each name is allocated a score when the random int array is generated.我需要它工作,以便在生成随机 int 数组时为每个名称分配一个分数。 I then need to keep track of the score for each name in the string array and when one name gets to a certain score they are the winner.
然后我需要跟踪字符串数组中每个名字的分数,当一个名字达到某个分数时,他们就是赢家。
Any help would be massively appreciated as I am just beginning.任何帮助将不胜感激,因为我才刚刚开始。
There's multiple ways of doing this, the best I would think is to create a class for it.有多种方法可以做到这一点,我认为最好的方法是为它创建一个类。
class Player {
String name;
int score;
}
Then in your main code where you generate the random numbers keep an Array of players.然后在您生成随机数的主代码中保留一组玩家。
Player[] players;
Alternatively you could use a HashMap<String, Integer>
but using Objects lets you expand more easily in the future.或者,您可以使用
HashMap<String, Integer>
但使用 Objects 可以让您在将来更轻松地扩展。
You need to start by declaring a random number generator, then implement it into a 2d array.您需要首先声明一个随机数生成器,然后将其实现为二维数组。
Random a=new Random();
Filling the array using a loop, with int num=a.nextInt(50);
使用循环填充数组,
int num=a.nextInt(50);
String array[i][0]=a
after a being converted to a String, and array[i][1]
being the names. String array[i][0]=a
转换为 String 后的 a, array[i][1]
为名称。 This should make tracking the results easier.这应该使跟踪结果更容易。
我可能会使用 TreeMap 将数字映射到字符串数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.