Java Reference
In-Depth Information
It's also possible to choose integers at random from sets of values other than ranges of
consecutive integers. For example, to obtain a random value from the sequence 2, 5, 8, 11
and 14, you could use the statement
int
number =
2
+
3
* randomNumbers.nextInt(
5
);
In this case,
randomNumbers.nextInt(5)
produces values in the range 0-4. Each value
produced is multiplied by 3 to produce a number in the sequence 0, 3, 6, 9 and 12. We
add 2 to that value to
shift
the range of values and obtain a value from the sequence 2, 5,
8, 11 and 14. We can generalize this result as
int
number =
shiftingValue
+
differenceBetweenValues
* randomNumbers.nextInt(
scalingFactor
);
where
shiftingValue
specifies the first number in the desired range of values,
difference-
BetweenValues
represents the
constant difference
between consecutive numbers in the se-
quence and
scalingFactor
specifies how many numbers are in the range.
A Note About Performance
Using
SecureRandom
instead of
Random
to achieve higher levels of security incurs a signif-
icant performance penalty. For “casual” applications, you might want to use class
Random
from package
java.util
—simply replace
SecureRandom
with
Random
.
Types
A popular game of chance is a dice game known as craps, which is played in casinos and
back alleys throughout the world. The rules of the game are straightforward:
You roll two dice. Each die has six faces, which contain one, two, three, four, five and
six spots, respectively. After the dice have come to rest, the sum of the spots on the two
upward faces is calculated. If the sum is 7 or 11 on the first throw, you win. If the sum
is 2, 3 or 12 on the first throw (called “craps”), you lose (i.e., the “house” wins). If the
sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes your “point.” To win,
you must continue rolling the dice until you “make your point” (i.e., roll that same
point value). You lose by rolling a 7 before making your point.
Figure 6.8 simulates the game of craps, using methods to implement the game's logic. The
main
method (lines 21-65) calls the
rollDice
method (lines 68-81) as necessary to roll
the dice and compute their sum. The sample outputs show winning and losing on the first
roll, and winning and losing on a subsequent roll.
1
// Fig. 6.8: Craps.java
2
// Craps class simulates the dice game craps.
3
import
java.security.SecureRandom;
4
5
public class
Craps
6
{
7
// create secure random number generator for use in method rollDice
8
private static final
SecureRandom randomNumbers =
new
SecureRandom();
Fig. 6.8
|
Craps
class simulates the dice game craps. (Part 1 of 3.)