Deck of Cards in Java – Interview Question

Introduction

A deck of cards typically consists of 52 cards, divided into 4 suits (Hearts, Diamonds, Clubs, Spades) with 13 ranks each (2 through 10, Jack, Queen, King, Ace). In this post, we'll walk through how to simulate a deck of cards in Java. This involves creating Card and Deck classes, shuffling the deck, and dealing cards.

Problem Statement

We need to design a Java program that:

  1. Simulates a deck of 52 playing cards.
  2. Allows shuffling of the deck.
  3. Allows dealing cards from the deck.
  4. Ensures no card is dealt more than once.
  5. Supports basic operations such as displaying the remaining cards in the deck.

Components

  1. Card Class: Represents an individual card with a suit and rank.
  2. Deck Class: Represents a deck of 52 cards, supports shuffling, dealing, and displaying the deck.

Java Code

1. Card Class

package deckofcards;

public class Card {
    private final Suit suit;
    private final Rank rank;

    public Card(Suit suit, Rank rank) {
        this.suit = suit;
        this.rank = rank;
    }

    public Suit getSuit() {
        return suit;
    }

    public Rank getRank() {
        return rank;
    }

    @Override
    public String toString() {
        return rank + " of " + suit;
    }
}
  • The Card class has two properties: suit and rank, both of which are represented by enums (defined below). The toString method returns a string representation of the card (e.g., "Ace of Spades").

2. Suit Enum

package deckofcards;

public enum Suit {
    HEARTS, DIAMONDS, CLUBS, SPADES;
}
  • The Suit enum defines the four suits in a deck of cards: Hearts, Diamonds, Clubs, and Spades.

3. Rank Enum

package deckofcards;

public enum Rank {
    TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE;
}
  • The Rank enum defines the 13 ranks in a deck of cards: Two through Ten, Jack, Queen, King, and Ace.

4. Deck Class

package deckofcards;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Deck {
    private final List<Card> cards;

    public Deck() {
        cards = new ArrayList<>();

        // Initialize deck with 52 cards
        for (Suit suit : Suit.values()) {
            for (Rank rank : Rank.values()) {
                cards.add(new Card(suit, rank));
            }
        }
    }

    // Shuffle the deck
    public void shuffle() {
        Collections.shuffle(cards);
    }

    // Deal one card from the deck
    public Card dealCard() {
        if (cards.isEmpty()) {
            throw new IllegalStateException("No cards are left in the deck!");
        }
        return cards.remove(cards.size() - 1); // Remove and return the last card
    }

    // Get the number of cards left in the deck
    public int cardsLeft() {
        return cards.size();
    }

    // Display all remaining cards in the deck
    public void displayDeck() {
        for (Card card : cards) {
            System.out.println(card);
        }
    }
}
  • The Deck class:
    • Initializes a list of 52 cards in the constructor.
    • Has a shuffle method to shuffle the deck using Collections.shuffle().
    • Has a dealCard method that deals the last card in the list (removing it from the deck).
    • Has a cardsLeft method to get the number of remaining cards.
    • Has a displayDeck method to print all the remaining cards in the deck.

5. Main Class

package deckofcards;

public class Main {
    public static void main(String[] args) {
        Deck deck = new Deck();  // Initialize the deck

        System.out.println("Shuffling the deck...");
        deck.shuffle();  // Shuffle the deck

        System.out.println("\nDealing 5 cards:");
        for (int i = 0; i < 5; i++) {
            System.out.println(deck.dealCard());
        }

        System.out.println("\nRemaining cards in the deck:");
        deck.displayDeck();  // Display the remaining cards

        System.out.println("\nNumber of cards left: " + deck.cardsLeft());
    }
}
  • The Main class demonstrates the usage of the Deck class. It shuffles the deck, deals 5 cards, displays the remaining cards, and shows the count of cards left in the deck.

Example Output:

Here’s an example run:

Shuffling the deck...

Dealing 5 cards:
SEVEN of HEARTS
NINE of CLUBS
QUEEN of DIAMONDS
ACE of SPADES
THREE of CLUBS

Remaining cards in the deck:
TWO of HEARTS
THREE of DIAMONDS
...
KING of HEARTS
FOUR of SPADES
TWO of SPADES

Number of cards left: 47
Deck of Cards in Java – Interview Question

The shuffle() method uses a random seed, so the order of cards will change every time you run the program

Conclusion

This Java program simulates a deck of 52 playing cards. It supports shuffling, dealing, and displaying the remaining cards in the deck. The code is modular, with separate classes for the card, deck, and the enums for suits and ranks. This design makes the program easy to extend and modify for additional features, such as multiple decks or different types of games.

Comments