D.9.1. Scaling and Shifting of Random Numbers

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(

Get Android™ How to Program, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.