Lee
Lee

Reputation: 1

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.

Upvotes: 0

Views: 66

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201399

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

Upvotes: 3

Related Questions