After successfully completing this lab you will be able to use a switch statement to count the number of times a random number is generated and use the count to print a histogram to visually inspect the distribution of random numbers.
You tested the random number generator in the Random class earlier this semester (Lab02a). That program required two lines of code to generate and print each number. That program clearly did not scale (the program would need 10,000 lines of code to generate and print 5000 numbers). Furthermore, that program required you to inspect the numbers to verify that the numbers were random. This lab will print a histogram enabling you to visualize the distribution of numbers.
You will develop a program to count the number of times each number in the range is generated. Your program will generate 100 numbers in the range [0, 9] and you will print a histogram similar to the histogram shown below.
0 ******** 1 *********** 2 ****** 3 **************** 4 ************** 5 ***** 6 ************ 7 *********** 8 ******** 9 *********
To print the histogram shown above, your program must record the number of times each number is generated. That is, the program will record the number of times 0 is generated, the number of times 1 is generated, the number of times 2 is generated, and so on. In the histogram above, the number 2 was generated 6 times, so there are 6 asterisks after the number 2.
Create a class named RandomSrv.java and import the Random class.
import java.util.Random;
Develop a method named generateNumbers that takes one parameter named total, an integer representing how many numbers the method will generate. Follow the instructions below to develop this method incrementally.
In the RandomSrv class, create a method named print that takes two integer parameters: num and count. The parameter num represents a number in the range and count represents the number of times num was generated.
Referring to the histogram shown above, the number 0 was generated 8 times. The input and output for the print method is shown below.
print(0, 8) will print "0 ********"
Use the RandomDrv driver to test the print method. Implement three test cases: (0, 0), (1, 1), and (2, x) where x is any number greater than 1. (These are not pass/fail test cases. You will visually inspect the output of these tests.)
Extend the generateNumbers method to call the print method ten times, once with each counter, to print the histogram.
Modify the RandomDrv driver to generate and print 100 numbers. Execute the test driver a few times to convince yourself that the distribution of numbers is random.
Submit RandomSrv.java and RandomDrv.java to the L06a dropbox on D2L.