ITEC 120
L02a: Testing the Random class

Objectives

In this lab you will call and test methods. You will learn to generate a random number within a given range. We will use random numbers in many of our assignments this semester. Read the entire assignment and bring questions to class.

Assignment

The Random class generates a sequence of random numbers.  The Random class provides a method named nextInt that returns the next integer in a sequence.  You will learn to use this method by developing learning tests.  You will not read any documentation. You will use black-box tests (i.e., you will not look at the method's code) to understand how to use the method. 

  1. Create a test driver named RandomTest that imports the Random class from the java.util package (the same package as the Scanner). Your test driver has one method, the main method. 
  2. Create a constant named MAX with the value 3. 
  3. Create an instance of the Random class – create a variable named random and assign the variable to a new instance of Random just like you create a new instance of the Scanner. 
  4. Use the variable random to make ten calls to the nextInt method and print the result of each call.  The nextInt method requires one integer parameter.  Pass MAX with each call.  Each call to nextInt is identical.  Write and test one call.  When the call is working, copy and paste the call until you have ten calls. 
  5. Compile and execute your test driver. Your test driver should print ten numbers. Plot the ten numbers on a histogram. (Do this in a new document in any editor you choose - it can be a word document or a text file.) Wikipedia provides a good explanation of histograms.
  6. Your histogram should look something like this:

    MAX = 3
    
    0 * * * *
    1 * * *
    2 * * *

    This histogram indicates that the program that was run generated four zeros, three ones, and three twos. If you run the program again, the output would be likely be different.

  7. Now change your program to generate 20 numbers between 0 and 4. Make a histogram for that output in the same document with your first one.
  8. Answer these five questions in your document with the histograms to turn in:
    • How do the histograms help you determine if the distribution of values is random?
    • Write a description of how to use the nextInt method to generate random numbers. Describe what numbers will be generated for a given input (parameter to nextInt).
    • How would you use the nextInt method to generate a random number between 1 and 10 (inclusive)?
    • How would you use nextInt to generate a random number between 5 and 17 (inclusive)?
    • How would you use nextInt to getnerate a randome number between x and y (inclusive)?

Submit Your Assignment

Submit two files to the L02a dropbox on D2L : RandomTest.java and the document with two histograms and answers to the five questions above.