To demonstrate random numbers, let’s show to simulate rolling a six-sided die. We begin by using nextInt
to produce random values in the range 0–5, as follows:
face = randomNumbers.nextInt( 6 );
The argument 6
—called the scaling factor—represents the number of unique values that nextInt
should produce (in this case six—0, 1, 2, 3, 4 and 5). This manipulation is called scaling the range of values produced by Random
method nextInt
.
A six-sided die has the numbers 1–6 on its faces, not 0–5. So we shift the range of numbers produced by adding a shifting value—in this case 1—to our previous result, as in
face = 1 + randomNumbers.nextInt( 6 );
The shifting value (1
) specifies the first value in the desired range of random integers. The preceding statement assigns face
a random integer in the range 1–6. The numbers produced by nextInt
occur with approximately equal likelihood.