Java provides at least 2 ways to produce random numbers:
The method random is a pseudorandom number generator because
the number generated is not truly random, in a theoretical sense.
However, we must make do with the tools available to us and the
numbers are random enough for most purposes. The random method
returns a number (type double) that is greater than or equal to 0.0
but less than 1.0.
The random numbers we want to generate for most applications are whole
numbers. For example, the sides of a die are represented by the whole
numbers 1 through 6. So we must convert the double returned by the
random method to an integer in the desired range. Suppose the range
of integers we want is [min,max]. If X is a number returned by
random, we can convert it into a number Y such that Y is in the range
[min,max](i.e., min <= Y <= max), by applying the formula
There is a class called Random in java.util that contains a method called
nextInt. This method is less complicated to use than the Math.random method.
To generate a random number between 1 and 6 using this class, you
could write the following code (assuming this code is written within
some method body and that the class imports java.util):
Using the Math.random method
Random numbers are useful in many computer applications, particularly
in games and simulations. For example, to simulate a roll of a single
die, we can generate a number between 1 and 6 (inclusive). One way to
generate random numbers in a Java program is to use the static random
method of the Math class.
int randomNumber
= (int)(Math.floor(Math.random() * (max - min + 1)) + min);
So suppose I wanted to generate a random number between 1 and 6, as in
the roll of a die. The expression would be
int randomRoll
= (int)(Math.floor(Math.random() * 6 + 1));
The cast to int is necessary because Math.floor returns a double.
Using the Random class
Random rollDie = new Random();
int randomRoll = rollDie.nextInt(6) + 1;
The nextInt method with one int parameter returns a pseudorandom,
uniformly distributed int value between 0 (inclusive) and the
specified value (exclusive) (which explains why we add 1 to the
returned value).