Chapter 7 Java Assignment This assignment will focus on the use of loops, random
ID: 3586709 • Letter: C
Question
Chapter 7 Java Assignment
This assignment will focus on the use of loops, random numbers, named constants, and arrays.
Follow the directions below to submit Assignment 7:
1. Create a Java program.
2. The class name for the program should be 'RandomDistributionCheck'.
3. In the main method you should perform the following:
a. You should generate 10,000,000 random numbers between 0 - 19.
b. You should use an array to hold the number of times each random number is generated.
c. When you are done, generating random numbers, you should output the random number, the number of times it occurred, and the percentage of all occurrences. The output should be displayed using one line for each random number.
d. Use named constants for the number of iterations (10,000,000) and a second named constant for the number of unique random numbers to be generated (20).
This assignment will focus on the use of loops, random numbers, named constants, and arrays.
Assignment 7Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
//Defining the class.
class RandomDistributionCheck
{
//main() function
public static void main (String[] args) throws java.lang.Exception
{
final int NUMBER_OF_ITERATION = 10000000; // Number of iteration
final int ARRAY_SIZE = 20; // Range of random numbers which is also size of the array
int num,i;
/*Creating an array in which occurances of generated random number will be stored at their corresponding index. like occurances of 0 is stored at index 0,occurances of 1 is stored at index 1 and so on. */
int[] randomNumberArray = new int[20];
//Creating an object of Random class.
Random rn = new Random();
for(i=0;i<NUMBER_OF_ITERATION;i++)
{
num = rn.nextInt(20); //creating random number between 0 to 19.
//Increamenting the number of occurances of generated random number by one and storing it to their corresponding index.
randomNumberArray[num] += 1;
}
for(i=0;i<ARRAY_SIZE;i++)
{
// Printing the output in format which has stated in subpart "c" of the question.
//Here i is the generated random number which is same as index of the array.
//randomNumberArray[i] is the number of occurances of random number i.
System.out.println(" Random number "+ i + " occurs " +randomNumberArray[i] + " times and its overall precentage is "+((randomNumberArray[i]*100.0)/NUMBER_OF_ITERATION));
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.