简体   繁体   中英

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. 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. 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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