dimanche 14 février 2021

Convert a random number to a string using switch statements

I'm trying to write a program that generates a random number 1-4, and then using a switch statement, convert each number to a corresponding card suit (hearts-1, diamonds-2, clubs-3, spades-4).

Random rand = new Random();
        
int suit;
suit = rand.nextInt(4)+1;
        
switch(suit) {
    case 1:
        String hearts = "hearts";
        break;
    case 2:
        String diamonds = "diamonds";
        break;
    case 3:
        String clubs = "clubs";
        break;
    case 4:
        String spades = "spades";
        break;
}
        

When all that is done and runs, I still only get the numbers that were generated itself. Rather than getting the string "diamonds" if the number 2 was generated. My goal is to concatenate a random suit, and a random number to go with that suit at the end, so to my understanding, using System.out.println(); inside of each switch case is not what I want.

The assignment instructions are: "Design and implement an application called Cards that randomly selects a playing card. First use a random number generator (Random class) to create a number in the range 1 to 4. Then convert the number to a suit (heart, diamond, club, or spade) using a switch statement. Next, use the random generator to create a random number in the range 1 to 13. Convert the number to ace, 2, 3, etc using another switch statement. Display the suit and the value of the chosen card."




Aucun commentaire:

Enregistrer un commentaire