Rank: Ace 2 3 4 5 6 7 8 9 10 J Q K
Spades: 0 1 2 3 4 5 6 7 8 9 10 11 12
Hearts: 13 14 15 16 17 18 19 20 21 22 23 24 25
Diamonds: 26 27 28 29 30 31 32 33 34 35 36 37 38
Clubs: 39 40 41 42 43 44 45 46 47 48 49 50 51
|
The suite of a card is one of: spades, hearts, diamonds and clubs.
The rank of a card is one of Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen and King.
A pair is (any) 2 cards of the same rank For example:
Ace of Spades and Ace of Hearts is a pair 2 of Clubs and 2 of Diamonds is a pair and so on |
In the last lesson, we looked at a program that shuffles a deck of cards and deals out some cards:
public class myProg
{
public static void main(String[] args)
{
int[] deck = new int[52];
for ( int i = 0; i < deck.length; i++ )
deck[i] = i; // 0, 1, 2, ...., 51
// Randomly shuffle the deck of cards
for (int i = 0; i < deck.length; i++)
{ // Generate an index randomly
int j = (int)(Math.random() * deck.length);
int temp = deck[i]; // Swap
deck[i] = deck[j];
deck[j] = temp;
}
// Deal 2 cards
int card1 = deck[0];
System.out.println( num2Card(card1) );
int card2 = deck[1];
System.out.println( num2Card(card2) );
// Write code here to check if you have a pair
}
public static String num2Card( int n )
{
/* --------------------------------------------------
Help arrays to translate suit and rank codes
to their English names
-------------------------------------------------- */
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
int cardSuit = n/13;
int cardRank = n%13;
return ranks[cardRank] + " of " + suits[cardSuit];
}
}
|
I have changed the program a little bit so it deals out 2 cards instead of 4 cards.
In this assignment, you are to add code in the program to check if the 2 cards is a pair. Prints the message "It is a pair" when the 2 cards is a pair and print "It is not a pair" otherwise.
It is not often that you will be dealt a pair. Run your program enough times until you see the message "It is a pair" to make sure your code is correct. You show see the message "It is a pair" after about 30 tries.