How to print a random card from a deck of cards in Java

In this tutorial, we will learn how to print a random card from the deck of playing cards in Java. This program can be done in multiple ways. You can use ArrayLists, collections, shuffle or even use Math.random() function. But I’m going to show you a simple and understandable way. We know that,

In a deck of cards, there are 52 cards.

  • 4 Signs
  • 13 Different values for each sign

The values of the cards are: A,K,Q,J,10,9,8,7,6,5,4,3,2,

The four signs are: “Spade”,”Club”,”Diamond”,”Heart”.

I have used two String arrays and then shuffled the cards, followed by printing one card at a time. The code is as follows, note the comments to understand in an explicit way.

Java program to print random cards from a deck of card

public class test {
    public static void main(String[] args) {
      String[] SUITS = {"Clubs", "Diamonds", "Hearts", "Spades"}; //initialising the suits of the deck in a String array named 'SUITS'
      String[] RANKS = {"2", "3", "4", "5", "6", "7", "8", "9", "10","Jack", "Queen", "King", "Ace"}; //initialising the ranks of the deck in a String array named 'RANKS'

        // initialize deck
        int n = SUITS.length * RANKS.length; // a deck consists of 4*13 cards
        String[] deck = new String[n];
        for (int i = 0; i < RANKS.length; i++) {
            for (int j = 0; j < SUITS.length; j++) {
                deck[SUITS.length*i + j] = RANKS[i] + " of " + SUITS[j];
            } 
        }

        // shuffle
        for (int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n-i)); //using random function
            String temp = deck[r];
            deck[r] = deck[i];
            deck[i] = temp; //swapping and shuffling
        }

        // print shuffled deck
        for (int i = 0; i < 1; i++) //printing one card at a time
       {
            System.out.println(deck[i]); //displaying a random card
        }
    }

}

The above program can be used to randomise a card from the deck of cards. You are not storing the card in any variable, you are just displaying it and hence every time you run the code, you will get a new random output.

Let’s run the code a couple of times and see the output.

OUTPUT  1:

10 of Clubs

OUTPUT 2

9 of Hearts

You can also check the code to print all the deck of cards in java here How to print deck of cards in Java

Do let me know in the comment section below, if you want the above Java program to be run by another method. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *