Java Reference
In-Depth Information
ListingĀ 7.2 gives the solution to the problem.
L ISTING 7.2
DeckOfCards.java
1 public class DeckOfCards {
2 public static void main(String[] args) {
3 int [] deck = new int [ 52 ];
4 String[] suits = { "Spades" , "Hearts" , "Diamonds" , "Clubs" };
5 String[] ranks = { "Ace" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" ,
6
create array deck
array of strings
array of strings
"10" , "Jack" , "Queen" , "King" };
7
8 // Initialize the cards
9 for ( int i = 0 ; i < deck.length; i++)
10 deck[i] = i;
11
12 // Shuffle the cards
13 for ( int i = 0 ; i < deck.length; i++) {
14 // Generate an index randomly
15 int index = ( int )(Math.random() * deck.length);
16 int temp = deck[i];
17 deck[i] = deck[index];
18 deck[index] = temp;
19 }
20
21 // Display the first four cards
22 for ( int i = 0 ; i < 4 ; i++) {
23 String suit = suits[deck[i] / 13 ];
24 String rank = ranks[deck[i] % 13 ];
25 System.out.println( "Card number " + deck[i] + ": "
26 + rank + " of " + suit);
27 }
28 }
29 }
initialize deck
shuffle deck
suit of a card
rank of a card
Card number 6: 7 of Spades
Card number 48: 10 of Clubs
Card number 11: Queen of Spades
Card number 24: Queen of Hearts
The program creates an array suits for four suits (line 4) and an array ranks for 13 cards in
a suit (lines 5-6). Each element in these arrays is a string.
The program initializes deck with values 0 to 51 in lines 9-10. The deck value 0 repre-
sents the card Ace of Spades, 1 represents the card 2 of Spades, 13 represents the card Ace of
Hearts, and 14 represents the card 2 of Hearts.
Lines 13-19 randomly shuffle the deck. After a deck is shuffled, deck[i] contains an
arbitrary value. deck[i] / 13 is 0 , 1 , 2 , or 3 , which determines the suit (line 23). deck[i]
% 13 is a value between 0 and 12 , which determines the rank (line 24). If the suits array is
not defined, you would have to determine the suit using a lengthy multi-way if-else state-
ment as follows:
if (deck[i] / 13 == 0 )
System.out.print( "suit is Spades" );
else if (deck[i] / 13 == 1 )
System.out.print( "suit is Hearts" );
else if (deck[i] / 13 == 2 )
System.out.print( "suit is Diamonds" );
else
System.out.print( "suit is Clubs" );
 
Search WWH ::




Custom Search