Java Reference
In-Depth Information
Random class for producing nondeterministic random numbers to help prevent such prob-
lems. From this point forward in the text, when we refer to “random numbers” we mean
“secure random numbers.”
Creating a SecureRandom Object
A new secure random-number generator object can be created as follows:
SecureRandom randomNumbers = new SecureRandom();
It can then be used to generate random values—we discuss only random int values here.
For more information on the SecureRandom class, see docs.oracle.com/javase/7/docs/
api/java/security/SecureRandom.html .
Obtaining a Random int Value
Consider the following statement:
int randomValue = randomNumbers.nextInt();
SecureRandom method nextInt generates a random int value. If it truly produces values
at random , then every value in the range should have an equal chance (or probability) of
being chosen each time nextInt is called.
Changing the Range of Values Produced By nextInt
The range of values produced by method nextInt generally differs from the range of val-
ues required in a particular Java application. For example, a program that simulates coin
tossing might require only 0 for “heads” and 1 for “tails.” A program that simulates the
rolling of a six-sided die might require random integers in the range 1-6. A program that
randomly predicts the next type of spaceship (out of four possibilities) that will fly across
the horizon in a video game might require random integers in the range 1-4. For cases like
these, class SecureRandom provides another version of method nextInt that receives an
int argument and returns a value from 0 up to, but not including, the argument's value.
For example, for coin tossing, the following statement returns 0 or 1.
int randomValue = randomNumbers.nextInt( 2 );
Rolling a Six-Sided Die
To demonstrate random numbers, let's develop a program that simulates 20 rolls of a six-
sided die and displays the value of each roll. We begin by using nextInt to produce ran-
dom values in the range 0-5, as follows:
int face = randomNumbers.nextInt( 6 );
The argument 6 —called the scaling factor —represents the number of unique values that
nextInt should produce (in this case six—0, 1, 2, 3, 4 and 5). This manipulation is called
scaling the range of values produced by SecureRandom method nextInt .
A six-sided die has the numbers 1-6 on its faces, not 0-5. So we shift the range of
numbers produced by adding a shifting value —in this case 1—to our previous result, as in
int face = 1 + randomNumbers.nextInt( 6 );
The shifting value ( 1 ) specifies the first value in the desired range of random integers. The
preceding statement assigns face a random integer in the range 1-6.
 
Search WWH ::




Custom Search