Random ClassPseudo-random numbers look and work like random numbers, but are generated from computer algorithms and so are not truly random.
Random class is actually a generator of
random numbers, not a random object itself. Just as
a die can be used to generate a random number between 1 and 6,
or
a coin can be used to generate heads or tails,
a Random object can be used to
generate random numbers or true/false values.
For example, the code
Random generator = new Random();
int randNum = generator.nextInt(10);
creates a random number generator and uses it to generate
one of the 10 numbers between 0 and 9 (the parameter specifies the
number of possible values). If we call nextInt(10)
repeatedly, we'll get a sequence of pseudo-random numbers
in that range, such as:
8, 5, 0, 0, 4, 3, 1, 3, 1, 0, 3, 6, 7, 0, 4, 4, 3, 9, 2, 8, ...
Random class is in the java.util package.
Consider a program simulating a person at lunch who randomly chooses between a cookie or an apple for dessert.
| Example: Choosing Randomly |
|---|
|