Search code examples
javaconstructorpoker

Creating a Deck of Cards?


I currently am working on a poker simulator and I am having trouble creating a deck of cards.

My current code creates the deck

public Deck() {
    int index = 0;
    cards = new Card[52];
    for(int cardValue = 1; cardValue <= 13; cardValue++) {
        for(int suitType = 0; suitType <= 3; suitType++) {
            cards[index] = new Card(cardValue, suitType);
            index++;
        }
    }
}

I need to make it look like:enter image description here

Anyway I can make it look like the above?

Also here is the code im using from another class for referral

/* Strings for use in toString method and also for identifying card
     * images */
    private final static String[] suitNames = {"s", "h", "c", "d"};
    private final static String[] valueNames = {"Unused", "A", "2", "3", "4", 
        "5", "6", "7", "8", "9", "10", "J", "Q", "K"};

    /**
     * Standard constructor.
     * @param value 1 through 13; 1 represents Ace, 2 through 10 for numerical
     * cards, 11 is Jack, 12 is Queen, 13 is King
     * @param suit 0 through 3; represents Spades, Hearts, Clubs, or Diamonds
     */
    public Card(int value, int suit) {
        if (value < 1 || value > 13) {
            throw new RuntimeException("Illegal card value attempted.  The " +
                    "acceptible range is 1 to 13.  You tried " + value);
        }
        if (suit < 0 || suit > 3) {
            throw new RuntimeException("Illegal suit attempted.  The  " + 
                    "acceptible range is 0 to 3.  You tried " + suit);
        }
        this.suit = suit;
        this.value = value;
    }

Solution

  • Just swap your for loops to create 13 cards per suit instead of 4 suits per card:

    public Deck() {
        int index = 0;
        cards = new Card[52];
        for(int suitType = 0; suitType <= 3; suitType++) {
            for(int cardValue = 1; cardValue <= 13; cardValue++) {
                cards[index] = new Card(cardValue, suitType);
                index++;
            }
        }
    }