If you initialize aRandomobject with a seed, you define the starting point for the random
sequence. If you use the same seed to initialize anotherRandomobject, you will extract the
same random sequence. If you want to generate different sequences, specify different seed
values. The easiest way to do this is to use the current time to seed aRandomobject. This
approach reduces the possibility of getting repeated sequences.
The public methods defined byRandomare shown in Table 18-6.
As you can see, there are seven types of random numbers that you can extract from a
Randomobject. Random Boolean values are available fromnextBoolean( ). Random bytes
can be obtained by callingnextBytes( ). Integers can be extracted via thenextInt( )method.
Long integers, uniformly distributed over their range, can be obtained withnextLong( ).
ThenextFloat( )andnextDouble( )methods return a uniformly distributedfloatanddouble,
respectively, between 0.0 and 1.0. Finally,nextGaussian( )returns adoublevalue centered
at 0.0 with a standard deviation of 1.0. This is what is known as abell curve.
Here is an example that demonstrates the sequence produced bynextGaussian( ). It
obtains 100 random Gaussian values and averages these values. The program also counts
the number of values that fall within two standard deviations, plus or minus, using increments
of 0.5 for each category. The result is graphically displayed sideways on the screen.
// Demonstrate random Gaussian values.
import java.util.Random;
class RandDemo {
public static void main(String args[]) {
Random r = new Random();
double val;
double sum = 0;
int bell[] = new int[10];
for(int i=0; i<100; i++) {
val = r.nextGaussian();
sum += val;
double t = -2;
Chapter 18: java.util Part 2: More Utility Classes 517
Method Description
boolean nextBoolean( ) Returns the nextbooleanrandom number.
void nextBytes(bytevals[ ]) Fillsvalswith randomly generated values.
double nextDouble( ) Returns the nextdoublerandom number.
float nextFloat( ) Returns the nextfloatrandom number.
double nextGaussian( ) Returns the next Gaussian random number.
int nextInt( ) Returns the nextintrandom number.
int nextInt(intn) Returns the nextintrandom number within the range zero ton.
long nextLong( ) Returns the nextlongrandom number.
void setSeed(longnewSeed) Sets the seed value (that is, the starting point for the random
number generator) to that specified bynewSeed.
TABLE 18-6 The Methods Defined byRandom