Java Reference
In-Depth Information
0
Ace
1
2
0
Spades
.
1
Hearts
cardNumber / 13 =
cardNumber % 13 =
.
2
Diamonds
10
Jack
3
Clubs
11
Queen
12
King
F IGURE 6.4
How cardNumber identifies a card's suit and rank number.
Listing 6.2 gives the solution to the problem.
L ISTING 6.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
Search WWH ::




Custom Search