ITEC 120
L07a: Testing Random with Arrays

Objectives

To successfully complete this lab you will use arrays and loops to develop a scalable program. Specifically, you will use an array to store a variable number of counters. Instead of keeping track of separate counter variables you will keep track of one variable, the handle to the array that contains all of the counters. By collecting the counters into an array your program will be able to loop through the counters instead of using separate statements to process each counter.

Testing Random, again

You will write a third program to test the random number generator in the Random class. Each of the three programs improves on the previous program. This will be the most efficient of the three programs requiring the least amount of code to generate any number of numbers. Your program will generate 200 numbers in the range [0, 20) and you will print a histogram to visualize the distribution of random numbers.

Assignment

In the RandomSrv class from L06a, develop a second method named gener­ateNumbers that takes two integer parameters: total and upperBound and returns an array of integers. The parameter total represents how many num­bers the method will generate. The parame­ter upperBound represents the upper bound of the range [0, upper­Bound) to be generated. Note that the upper bound is exclusive. Follow the instructions below to develop this method.

  1. Create an array named counters of size upperBound.
  1. Write a loop to generate total numbers in the range [0, upperBound).
  1. Write one line of code to increment the counter for the number that is generated.
  1. Return the array counters.

The counters array replaces the individual count variables from the previous lab.

Test your Method

Modify the RandomDrv class from L06a to call the new gener­ateNumbers method with parame­ter values 10 and 3. This will generate 10 numbers in the range [0, 3). In the driver, write a For loop to print the value of each counter in the array returned by the method. 

Print a Histogram

In the RandomSrv class, create a second method named print that takes one parameter, an array of integers. Write a For loop to step through the given array and call the first print method. Do not call System.out.print or System.out.println from this new method.

Modify the RandomDrv class to generate and print 200 numbers in the range [0, 20).

Learning Outcomes

This assignment has shown how the combination of variables, loops, and arrays enables a program to scale. The gener­ateNumbers method creates an array with a counter for each number in the range of numbers being generated. By storing the counters in an array the program is able to use loops to process the counters. This program is able to generate any number of num­bers with any upper bound without changing a single line of code.

Submit Your Assignment

Submit your modified RandomSrv.java and RandomDrv.java to the L07a dropbox on D2L.