Java Reference
In-Depth Information
Face Frequency
1 999501
2 1000412
3 998262
4 1000820
5 1002245
6 998760
Face Frequency
1 999647
2 999557
3 999571
4 1000376
5 1000701
6 1000148
Fig. 6.7
|
Roll a six-sided die 6,000,000 times. (Part 2 of 2.)
As the sample outputs show, scaling and shifting the values produced by
nextInt
enables the program to simulate rolling a six-sided die. The application uses nested control
statements (the
switch
is nested inside the
for
) to determine the number of times each side
of the die appears. The
for
statement (lines 20-46) iterates 6,000,000 times. During each
iteration, line 22 produces a random value from 1 to 6. That value is then used as the con-
trolling expression (line 25) of the
switch
statement (lines 25-45). Based on the
face
value,
the
switch
statement increments one of the six counter variables during each iteration of
the loop. This
switch
statement has no
default
case, because we have a
case
for every pos-
sible die value that the expression in line 22 could produce. Run the program, and observe
the results. As you'll see, every time you run this program, it produces
different
results.
When we study arrays in Chapter 7, we'll show an elegant way to replace the entire
switch
statement in this program with a
single
statement. Then, when we study Java SE
8's new functional programming capabilities in Chapter 17, we'll show how to replace the
loop that rolls the dice, the
switch
statement
and
the statement that displays the results
with a
single
statement!
Generalized Scaling and Shifting of Random Numbers
Previously, we simulated the rolling of a six-sided die with the statement
int
face =
1
+ randomNumbers.nextInt(
6
);
This statement always assigns to variable
face
an integer in the range
1
≤
face
≤
6
. The
width
of this range (i.e., the number of consecutive integers in the range) is
6
, and the
start-
ing number
in the range is
1
. In the preceding statement, the width of the range is deter-
mined by the number
6
that's passed as an argument to
SecureRandom
method
nextInt
,
and the starting number of the range is the number
1
that's added to
randomNumbers.nex-
tInt(6)
. We can generalize this result as
int
number =
shiftingValue
+ randomNumbers.nextInt(
scalingFactor
);
where
shiftingValue
specifies the
first number
in the desired range of consecutive integers
and
scalingFactor
specifies
how many numbers
are in the range.