Page 215 - Introduction to Programming with Java: A Problem Solving Approach
P. 215

                5.8 Problem Solving with Random Numbers (Optional) 181
 /******************************************************************
*
RandomTest.java
Dean & Dean
This program demonstrates methods of the Random class.
******************************************************************/
*
*
*
import java.util.Random;
public class RandomTest
{
  public static void main(String[] args)
  }
// end class RandomTest
{
Random random = new Random();
System.out.println(random.nextInt(Integer.MAX_VALUE));
System.out.println(5.0 + 0.8 * random.nextGaussian());
} // end main
Sample session:
 1842579217
4.242694469045554
Apago PDF Enhancer
Use new to invoke an explicit object constructor.
Figure 5.12 RandomTest program uses Random class methods to generate random numbers from different distributions
You can use the deterministic nature of the seeded random-number generator to make your life a lot easier when you are developing and debugging programs that use random numbers.
If you do not use a seeded random number generator, whenever a program gener-
ates a random number, what comes out will be a surprise, because it’s random! This unpredictability can be quite frustrating when you are trying to develop and test a program that uses random numbers, because every test run produces different numerical values. During development and testing, what you’d like is a fixed set of “random” numbers, which turn out to be exactly the same every time you rerun a program you’re testing.
To establish a fixed random-number test set, you could write a simple program that prints a particular set of random numbers. You could copy those particular numbers into assignment statements in your pro- gram, that is, hard code them in your program for development and testing. Then, after your program has been tested and verified, you could replace each hard-coded “random number” by a random-number genera- tor that produces a different number every time it’s invoked.
But the Random class provides a more elegant way to develop programs that have random variables. During development, use its one-parameter constructor with a fixed seed to produce exactly the same se- quence of randomly distributed numbers every time you run the program. Then, when all your bugs are fixed, simply delete the seed number from the Random constructor in the initialization statement at the be- ginning of your code, and—voila—your random-number generator produces completely different numbers from that time forward.
    When testing, fix your random numbers.
  

































































   213   214   215   216   217