Java Reference
In-Depth Information
Rolling a Six-Sided Die 20 Times
Figure 6.6 shows two sample outputs which confirm that the results of the preceding cal-
culation are integers in the range 1-6, and that each run of the program can produce a
different
sequence of random numbers. Line 3 imports class
SecureRandom
from the
java.security
package. Line 10 creates the
SecureRandom
object
randomNumbers
to pro-
duce random values. Line 16 executes 20 times in a loop to roll the die. The
if
statement
(lines 21-22) in the loop starts a new line of output after every five numbers to create a
neat, five-column format.
1
// Fig. 6.6: RandomIntegers.java
2
// Shifted and scaled random integers.
3
4
5
import
java.security.SecureRandom;
// program uses class SecureRandom
public class
RandomIntegers
6
{
7
public static void
main(String[] args)
8
{
9
// randomNumbers object will produce secure random numbers
SecureRandom randomNumbers =
new
SecureRandom();
10
11
12
// loop 20 times
13
for
(
int
counter =
1
; counter <=
20
; counter++)
14
{
15
// pick random integer from 1 to 6
16
int
face =
1
+ randomNumbers.nextInt(
6
);
17
18
System.out.printf(
"%d "
, face);
// display generated value
19
20
// if counter is divisible by 5, start a new line of output
21
if
(counter %
5
==
0
)
22
System.out.println();
23
}
24
}
25
}
// end class RandomIntegers
1 5 3 6 2
5 2 6 5 2
4 4 4 2 6
3 1 6 2 2
6 5 4 2 6
1 2 5 1 3
6 3 2 2 1
6 4 2 6 4
Fig. 6.6
|
Shifted and scaled random integers.
Rolling a Six-Sided Die 6,000,000 Times
To show that the numbers produced by
nextInt
occur with approximately equal likeli-
hood, let's simulate 6,000,000 rolls of a die with the application in Fig. 6.7. Each integer
from 1 to 6 should appear approximately 1,000,000 times.