Java Reference
In-Depth Information
each number in the array with the average to count the number of values above the average
(lines 17-20).
7.4 Case Study: Deck of Cards
The problem is to create a program that will randomly select four cards from a deck
of cards.
Key
Point
Say you want to write a program that will pick four cards at random from a deck of 52 cards.
All the cards can be represented using an array named deck , filled with initial values 0 to 51 ,
as follows:
int [] deck = new int [ 52 ];
VideoNote
Deck of cards
// Initialize cards
for ( int i = 0 ; i < deck.length; i++)
deck[i] = i;
Card numbers 0 to 12 , 13 to 25 , 26 to 38 , and 39 to 51 represent 13 Spades, 13 Hearts,
13 Diamonds, and 13 Clubs, respectively, as shown in Figure 7.2. cardNumber / 13 deter-
mines the suit of the card and cardNumber % 13 determines the rank of the card, as shown
in Figure 7.3. After shuffling the array deck , pick the first four cards from deck . The program
displays the cards from these four card numbers.
deck
[0]
.
.
.
[12]
[13]
.
.
.
[25]
[26]
.
.
.
[38]
[39]
.
.
.
[51]
deck
[0]
[1]
[2]
[3]
[4]
[5]
.
.
.
[25]
[26]
.
.
.
[38]
[39]
.
.
.
[51]
0
.
.
.
12
1 .
.
.
25
2 .
.
.
38
39
.
.
.
51
0
.
.
.
12
13
.
.
.
25
26
.
.
.
38
39
.
.
.
51
6
48
11
24
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Card number 6 is the
7 (6 % 13 = 6) of
Spades (7 / 13 is 0)
Card number 48 is the
10 (48 % 13 = 9) of
Clubs (48 / 13 is 3)
13 Spades ( )
13 Hearts ( )
Card number 11 is the
Queen (11 % 13 = 11) of
Spades (11 / 13 is 0)
Random shuffle
Card number 24 is the
Queen (24 % 13 = 11) of
Hearts (24 / 13 is 1)
13 Diamonds ( )
13 Clubs ( )
F IGURE 7.2
52 cards are stored in an array named deck .
0
Ace
1
2
0
Spades
.
1
Hearts
cardNumber / 13 =
cardNumber % 13 =
.
2
Diamonds
10
Jack
3
Clubs
11
Queen
12
King
F IGURE 7.3
CardNumber identifies a card's suit and rank number.
 
 
 
Search WWH ::




Custom Search