img
Method
Description
boolean nextBoolean( )
Returns the next boolean random number.
void nextBytes(byte vals[ ])
Fills vals with randomly generated values.
double nextDouble( )
Returns the next double random number.
float nextFloat( )
Returns the next float random number.
double nextGaussian( )
Returns the next Gaussian random number.
int nextInt( )
Returns the next int random number.
int nextInt(int n)
Returns the next int random number within the range zero to n.
long nextLong( )
Returns the next long random number.
void setSeed(long newSeed) Sets the seed value (that is, the star ting point for the random
number generator) to that specified by newSeed.
TABLE 18-6
The Methods Defined by Random
If you initialize a Random object with a seed, you define the starting point for the random
sequence. If you use the same seed to initialize another Random object, 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 a Random object. This
approach reduces the possibility of getting repeated sequences.
The public methods defined by Random are shown in Table 18-6.
As you can see, there are seven types of random numbers that you can extract from a
Random object. Random Boolean values are available from nextBoolean( ). Random bytes
can be obtained by calling nextBytes( ). Integers can be extracted via the nextInt( ) method.
Long integers, uniformly distributed over their range, can be obtained with nextLong( ).
The nextFloat( ) and nextDouble( ) methods return a uniformly distributed float and double,
respectively, between 0.0 and 1.0. Finally, nextGaussian( ) returns a double value centered
at 0.0 with a standard deviation of 1.0. This is what is known as a bell curve.
Here is an example that demonstrates the sequence produced by nextGaussian( ). 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;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home