我对如何从程序中获取某个范围内的随机生成的数字,将其存储到数组中以及从数组中读取并打印出生成该数字的次数感到困惑。
对于随机导入,我正在使用java.util.concurrent.ThreadLocalRandom
;
public static void main(String[] args) {
char quitOption = 'q';
char continueOption = 'c';
char input;
int[] myArray;
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
if (input == continueOption || input == 'C') {
roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} else if (input == quitOption || input == 'Q') {
System.exit(0);
}
} while (continueOption == 'c' || continueOption == 'C');
}
答案 0 :(得分:2)
我会用HashMap<Integer, Integer>
来称呼它rollMap
。
每次滚动都会得到int currentRoll = randomRoll()
。
如果我是你,我会说:
if(rollMap.containsKey(currentRoll)){
rollMap.put(currentRoll, rollMap.get(currentRoll) + 1);
}else{
rollMap.put(currentRoll, 1);
}
然后您可以说出每个数字被滚动了多少次:
System.out.println(rollMap.get(<rollid>));
答案 1 :(得分:1)
您必须弄清楚如何克服两个问题:
找出Array
固定大小的卷数
计算数字滚动多少次
您可以使用List
,然后使用诸如Collections.frequency
之类的内置方法,或者如果您仅限于Array
,请检查以确保添加另一个数字不会超出范围,(然后将其复制到新的Array
中),然后遍历Array
并计算每个数字出现多少次。
但是,我们知道将要发生的数字范围。因此,为什么不使用六个元素初始化Array
,而让0
为1
,让1
为2
,依此类推。然后,每次滚动该数字时,我们都会增加相应数字的索引。像这样:
int roll = ThreadLocalRandom.current().nextInt(1, 6);
arr[roll -1]++;
因此,如果将两个相加,则将一个添加到1th
索引中:
[0, 1, 0, 0, 0, 0]
以此类推。然后,当您需要对索引进行计数时,它会发生一个简单的循环:
for(int i = 0; i < arr.length; i++) {
System.out.println(i + 1 + " occurs: " + arr[i] + " times");
}
您还使循环变得复杂了。可以简化为:
char input;
int[] myArray = new int[6];
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
myArray[roll -1]++;
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} while (input == 'c' || input == 'C');
for(int i = 0; i < myArray.length; i++ ) {
System.out.println(i + 1 + " occurs: " + myArray[i] + " times");
}
示例运行:
Roll is 4
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
q
1 occurs: 3 times
2 occurs: 0 times
3 occurs: 2 times
4 occurs: 1 times
5 occurs: 0 times
6 occurs: 0 times