319,984 views
16 votes
16 votes
Draw a Card. Write a program to simulate drawing a card. Your program will randomly select one card from a deck of 52 playing 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: in The card you picked is Jack of Heart The program should use at a minimum: sequence, selection, arrays, and random numbers.

User Kasper Juner
by
2.9k points

1 Answer

16 votes
16 votes

Answer:

Step-by-step explanation:

The following code is written in Java. It is a function that creates a Random object to generate random values, then uses those values to choose a random rank and suit using switch statements. It then saves the rank and suit into a String variable in the correct format and finally prints the card that was picked to the screen. The function was called 4 times in the main method and the output can be seen in the attached image below.

public static void randomCardGenerator() {

Random rand = new Random();

int rank = rand.nextInt(14)+1;

int suit = rand.nextInt(4)+1;

String chosenCard = "";

switch (rank) {

case 1: chosenCard += "Ace"; break;

case 2: chosenCard += "1"; break;

case 3: chosenCard += "2"; break;

case 4: chosenCard += "3"; break;

case 5: chosenCard += "4"; break;

case 6: chosenCard += "5"; break;

case 7: chosenCard += "6"; break;

case 8: chosenCard += "7"; break;

case 9: chosenCard += "8"; break;

case 10: chosenCard += "9"; break;

case 11: chosenCard += "10"; break;

case 12: chosenCard += "Jack"; break;

case 13: chosenCard += "Queen"; break;

case 14: chosenCard += "Kind"; break;

default: System.out.println("Wrong Value");

}

chosenCard += " of ";

switch (suit) {

case 1: chosenCard += "Clubs"; break;

case 2: chosenCard += "Diamonds"; break;

case 3: chosenCard += "Hearts"; break;

case 4: chosenCard += "Spades"; break;

default: System.out.println("Invalid Suit");

}

System.out.println(chosenCard);

}

Draw a Card. Write a program to simulate drawing a card. Your program will randomly-example-1
User Roman Grinev
by
3.3k points