**3.24 (Game: pick a card) Write a program that simulates picking a card from a deck
of 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Jack, Queen, King) and suit (Clubs, Diamonds, Hearts, Spades) of the card.
Here is a sample run of the program:
The card you picked is Jack of Hearts
The card you picked is Jack of Hearts
public class ProgrammingEx3_24 { public static void main(String[] args) { int card = (int) (Math.random() * 52.0); // pick a card 0-51 int rank = card / 4; // determine the rank 0-12 int suit = card % 4; // determine the suit 0-3 String strRank = ""; String strSuit = ""; switch (rank) { case 0: strRank = "Ace"; break; case 10: strRank = "Jack"; break; case 11: strRank = "Queen"; break; case 12: strRank = "King"; break; default: strRank = "" + (rank + 1); break; } switch (suit) { case 0: strSuit = "Clubs"; break; case 1: strSuit = "Diamonds"; break; case 2: strSuit = "Hearts"; break; case 3: strSuit = "Spades"; break; } System.out.print("The card you picked is " + strRank +" of " + strSuit ); } }
another solution by Y. Daniel LiangY
ReplyDeletefinal int NUMBER_OF_CARDS = 52;
// Pick a card
int number = (int)(Math.random() * NUMBER_OF_CARDS);
System.out.print("The card you picked is ");
if (number % 13 == 0)
System.out.print("Ace of ");
else if (number % 13 == 10)
System.out.print("Jack of ");
else if (number % 13 == 11)
System.out.print("Queen of ");
else if (number % 13 == 12)
System.out.print("King of ");
else
System.out.print((number % 13) + " of ");
if (number / 13 == 0)
System.out.println("Clubs");
else if (number / 13 == 1)
System.out.println("Diamonds");
else if (number / 13 == 2)
System.out.println("Hearts");
else if (number / 13 == 3)
System.out.println("Spades");