我对如何从程序中获取一定范围内的随机生成的数字,将其存储到数组中,然后从数组中读取并打印出该数字生成的次数感到有点困惑。
对于随机导入,我使用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');
}
最佳答案
我会使用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>));
关于java - 在数组中存储随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53870973/