# Deck of cards problem

• 02-16-2011, 07:46 PM
VelvetMirror
Deck of cards problem
I'm following the Official Java Tutorial and I'm doing an exercise in order to incorporate enums to a Deck of Cards example.

I have 5 classes: Rank (an enum of the ranks), Suit (an enum of the suits), Card (a class describing a single Card), Deck (a class describing a deck of cards), and DisplayDeck (which displays the cards in the decks).

The solution solves the Card class, the Deck class and the enum classes (Rank and Suit) so I have written a DisplayDeck class in order to show the deck of cards.

Here are my classes, in bold it's the new code I've added (at the last two classes) and although it works fine, I would like to know if it is the right way to do it or if there is a better or simpler way to go around it:

1. Rank class:

Code:

package deckcardswithenum;

public enum Rank {

ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN,
EIGHT, NINE, TEN, JACK, QUEEN, KING
}

2. Suit class:

Code:

package deckcardswithenum;

public enum Suit {

}

3. Card class:

Code:

package deckcardswithenum;

public class Card {

private final Suit suit;
private final Rank rank;

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

public Rank getRank() {
return rank;
}

public Suit getSuit() {
return suit;
}

@Override
public String toString() {
return rank + " of " + suit;
}
}

4. Deck class:

Code:

package deckcardswithenum;

public class Deck {

private static Card[] cards = new Card[52];

public Deck() {
int i = 0;

for (Suit suit : Suit.values()) {
for (Rank rank : Rank.values()) {
cards[i++] = new Card(rank, suit);
}
}
}
[b]
public Card[] getCards() {
return cards;
}[/b]
}

5. DisplayDeck class:

Code:

[b]package deckcardswithenum;

public class DisplayDeck {

public static void main(String[] args) {
Deck deck = new Deck();
Card[] cards = deck.getCards();

int i = 0;

for (Suit suit : Suit.values()) {
for (Rank rank : Rank.values()) {
System.out.println(cards[i++]);
}
}
}
}[/b]

• 02-16-2011, 07:56 PM
JosAH
Why don't you simply make that loop in your last class like this?

Code:

for (Card c: deck.getCards())
System.out.println(c);

kind regards,

Jos
• 02-16-2011, 09:02 PM
VelvetMirror
It seemed to me that my code was redundant but I couldn't point where, I didn't understand well enough the use of "for" loop for collections.

You are right, that's a far better solution.

Thanks.