Answer: The java program to generate 100 random numbers and count their occurrence is shown below.
import java.util.Random;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
int[]count = new int[10];
// temporarily stores the randomly generated number
int num;
for(int i=0; i<10; i++)
{
// initialize count of all digits from 0 to 9 to zero
count[i] = 0;
}
for(int i=0; i<100; i++)
{
// generates 100 random numbers or integers from 0 through 9
num = (int) (Math.random() * 10);
for(int j=0; j<10; j++)
{
// compare each randomly generated number with digits from 0 to 9 and increment their count accordingly
if(num == j)
count[j] = count[j]+1;
}
}
System.out.println("The count of randomly generated numbers is shown below.");
for(int i=0; i<10; i++)
{
System.out.println("Count of "+i+" is "+ count[i]);
}
}
}
OUTPUT
The count of randomly generated numbers is shown below.
Count of 0 is 10
Count of 1 is 8
Count of 2 is 13
Count of 3 is 10
Count of 4 is 9
Count of 5 is 13
Count of 6 is 7
Count of 7 is 11
Count of 8 is 9
Count of 9 is 10
Explanation: This program declares an integer array of size 10 and initializes it to 0.
Random numbers are generated as shown. The number is randomly generated in an outer for loop with executes 100 times for 100 numbers.
(int) (Math.random() * 10)
The package java.util.Math is imported to serve the purpose.
The above code generates random numbers which can be floating numbers. The integer part is extracted using (int).
This yields the digits from 0 through 9.
For every occurrence of digits from 0 to 9, the count of the index of the respective digit is incremented.
To serve this purpose, inner for loop is implemented. The variable used in this loop is compared with the random number and index of count incremented accordingly. The inner for loop runs 10 times at the maximum, in order to match random number with 0 through 9.
Lastly, the occurrence of every digit from 0 to 9 is displayed.