How to pick 5 random cards from a 52‑card deck in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
A standard deck of 52 playing cards consists of four suits:
spades (♠), hearts (♥), diamonds (♦), and clubs (♣).

Each suit contains 13 ranks:
Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King.

Cards of spades and clubs are black, while hearts and diamonds are red.

Color is informational only — it does not affect shuffling or random selection.
*/

/**
    This program picks 5 random cards from a standard 52‑card deck.

    It uses:
    - ArrayList<String> to store the deck
    - Collections.shuffle for efficient randomization
    - Random for high‑quality randomness

    Algorithm:
    1. Build the deck (52 strings).
    2. Shuffle using Collections.shuffle.
    3. Print the first 5 cards.
*/

public class RandomCards {

    // Build a full 52‑card deck
    public static List<String> buildDeck() {
        String[] ranks = {
            "2","3","4","5","6","7","8","9","10","J","Q","K","A"
        };

        String[] suits = {
            "Clubs", "Diamonds", "Hearts", "Spades"
        };

        List<String> deck = new ArrayList<>(52);

        // Combine each rank with each suit → 52 unique cards
        for (String suit : suits) {
            for (String rank : ranks) {
                deck.add(rank + " of " + suit);
            }
        }

        return deck;
    }

    // Shuffle the deck using Java's built‑in shuffle
    public static void shuffleDeck(List<String> deck) {
        Random rng = new Random();  // Seeds automatically using system time
        Collections.shuffle(deck, rng);
    }

    public static void main(String[] args) {

        // Step 1: Build the deck
        List<String> deck = buildDeck();

        // Step 2: Shuffle the deck
        shuffleDeck(deck);

        // Step 3: Draw the first 5 cards
        System.out.println("Your 5 random cards:");
        for (int i = 0; i < 5; i++) {
            System.out.println(deck.get(i));
        }
    }
}


/*
run:

Your 5 random cards:
7 of Spades
2 of Hearts
K of Hearts
9 of Hearts
J of Spades

*/

 



answered 1 day ago by avibootz
...