简体   繁体   English

如何在Java FOR LOOP中获得指定随机数的数量

[英]How to get the amount of the specified random number in Java FOR LOOP

I would like to ask how to get the amount of the specified number. 我想问一下如何获得指定数量的金额。 For example, I want to see the amount of the number 1234 which has been generated in the random generator. 例如,我想查看在随机生成器中生成的数字1234的数量。 I would like it to print out the amount of the specified number which has been generated. 我希望打印出已生成的指定数量的金额。

Merry Christmas. 圣诞节快乐。 Thanks for your reply. 感谢您的回复。

Assuming you want to count the number of times a given random number was generated, and given an int value MAX with the maximum random number possible and an int COUNT for the number of random values to generate, you might create an array of counts and then print it. 假设您要计算生成给定随机数的次数,并给定一个intMAX (可能的最大随机数)和一个int COUNT (生成的随机值的counts ,则可以创建一个counts数组,然后打印它。 Something like 就像是

int COUNT = 1000;
int MAX = 100;
Random rand = new Random();
int[] counts = new int[MAX]; // <-- 0, MAX all initialized at 0.
for (int i = 0; i < COUNT; i++) {
  counts[rand.nextInt(MAX)]++; // <-- add one at a random index between 
                               //     0 (inclusive) and MAX (exclusive).
}
System.out.println(Arrays.toString(counts));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM