Java Reference
In-Depth Information
The
Random
Object
Java includes an object called
Random
that can be used to generate many different
types of random numbers. In this section, we discuss only how to generate random
integers and doubles from a uniform distribution (this is when every number that
could possibly be generated has an equally likely chance to appear) but the
Random
class
supports other distributions.
To use the
Random
class, we first have to import it just like we imported the
Scanner
class:
import
java.util.Random;
Next, we have to create an object of type
Random
that can generate the random
numbers for us. This follows the same pattern as creating a
Scanner
object to read
from the keyboard.
Random randomGenerator =
new
Random();
Similarly, just as you created only one
Scanner
object to read in all of your
keyboard inputs, in general you should create only one
Random
object to generate all
of your random numbers. In particular, older versions of Java used the computer's
clock to seed the random number generator. This meant that two
Random
objects
created within the same millisecond would generate the same sequence of numbers.
Newer versions of Java do not have this limitation, but normally only one instance of a
Random
object is needed.
To generate a random integer in the range of all possible integers, use
int
r = randomGenerator.nextInt();
To generate a random integer in the range from 0 to
n
-1, use
int
r = randomGenerator.nextInt(n);
If you want a random number in a different range, then you can scale the number
by adding an offset. For example, to generate a random number that is 4, 5, or 6, use
int
r = randomGenerator.nextInt(3) + 4;
This generates a number that is 0, 1, or 2 and then adds 4 to get a number that is 4,
5, or 6.
To generate a random
double
, use
double
r = randomGenerator.nextDouble();
This returns a number that is greater than or equal to 0.0 but less than 1.0. Display 3.11
demonstrates flipping a virtual coin five times by generating five random numbers that
are either 0 or 1, where 0 corresponds to tails and 1 corresponds to heads.