Java Reference
In-Depth Information
5
public class
DeckOfCards
6
{
7
private
Card[] deck;
// array of Card objects
8
private int
currentCard;
// index of next Card to be dealt (0-51)
9
private static final int
NUMBER_OF_CARDS
=
52
;
// constant # of Cards
10
// random number generator
11
private
static final
SecureRandom randomNumbers =
new
SecureRandom();
12
13
// constructor fills deck of Cards
14
public
DeckOfCards()
15
{
16
String[] faces = {
"Ace"
,
"Deuce"
,
"Three"
,
"Four"
,
"Five"
,
"Six"
,
"Seven"
,
"Eight"
,
"Nine"
,
"Ten"
,
"Jack"
,
"Queen"
,
"King"
};
String[] suits = {
"Hearts"
,
"Diamonds"
,
"Clubs"
,
"Spades"
};
17
18
19
20
deck =
new
Card[
NUMBER_OF_CARDS
];
// create array of Card objects
21
currentCard =
0
;
// first Card dealt will be deck[0]
22
23
// populate deck with Card objects
for
(
int
count =
0
; count < deck.length; count++)
deck[count] =
new
Card(faces[count %
13
], suits[count /
13
]);
24
25
26
27
}
28
29
// shuffle deck of Cards with one-pass algorithm
30
public void
shuffle()
31
{
32
// next call to method dealCard should start at deck[0] again
33
currentCard =
0
;
34
35
// for each Card, pick another random Card (0-51) and swap them
36
for
(
int
first =
0
; first < deck.length; first++)
37
{
38
// select a random number between 0 and 51
39
int
second = randomNumbers.nextInt(
NUMBER_OF_CARDS
);
40
41
// swap current Card with randomly selected Card
42
Card temp = deck[first];
deck[first] = deck[second];
deck[second] = temp;
43
44
45
}
46
}
47
48
// deal one Card
49
public
Card dealCard()
50
{
51
// determine whether Cards remain to be dealt
52
if
(
currentCard < deck.length
)
53
return
deck[currentCard++];
// return current Card in array
54
else
55
return
null
;
// return null to indicate that all Cards were dealt
56
}
57
}
// end class DeckOfCards
Fig. 7.10
|
DeckOfCards
class represents a deck of playing cards. (Part 2 of 2.)