Java Reference
In-Depth Information
3.4 The Random Class
The need for random numbers occurs frequently when writing software. Games
often use a random number to represent the roll of a die or the shuffle of a deck
of cards. A flight simulator may use random numbers to determine how often
a simulated flight has engine trouble. A program designed to help high school
students prepare for the SATs may use random numbers to choose the next ques-
tion to ask.
The Random class, which is part of the java.util class, represents a pseu-
dorandom number generator
. A random number generator picks a number at
random out of a range of values. A program that serves this role is technically
pseudorandom, because a program has no means to actually pick a number
randomly. A pseudorandom number generator performs a series of complicated
calculations, based on an initial seed value , and produces a number. Though they
are technically not random (because they are calculated), the values produced
by a pseudorandom number generator usually appear random, at least random
enough for most situations.
Figure 3.4 lists some of the methods of the Random class. The
nextInt method can be called with no parameters, or we can pass
it a single integer value. The version that takes no parameters gener-
ates a random number across the entire range of int values, includ-
ing negative numbers. Usually, though, we need a random number
within a more specific range. For instance, to simulate the roll of a
die, we might want a random number in the range of 1 to 6. The nextInt method
returns a value that's in the range from 0 to one less than its parameter. For
example, if we pass in 100, we'll get a return value that is greater than or equal
to 0 and less than or equal to 99.
KEY CONCEPT
A pseudorandom number generator
performs a complex calculation to
create the illusion of randomness.
Random ()
Constructor: creates a new pseudorandom number generator.
float nextFloat ()
Returns a random number between 0.0 (inclusive) and 1.0 (exclusive).
int nextInt ()
Returns a random number that ranges over all possible int values (positive
and negative).
int nextInt ( int num)
Returns a random number in the range 0 to num- 1.
FIGURE 3.4
Some methods of the Random class
 
Search WWH ::




Custom Search