Re: Shuffled Poker Deck
Martin Krainer wrote:
Hi all,
Im new to Java, and as Training for me I tried to build an Application,
which returns a shuffled Pokerdeck. (Random from 1 to 52)
Maybe you will laugh, but i needed a whole day to solve it, and I think its
even not good solution.
Well, at least it works, but please could you give me a hint, how to solve
this problem easier.
Heres the code:
[snip the code]
Well, it doesn't look all that great to me.
Here's one that looks better.
class Deck {
final java.util.List<Card> cards;
private static final int DECK_SIZE = Card.NUMBER_OF_CARD_TYPES;
public Deck() {
this.cards = new java.util.ArrayList<Card>();
for (int i = 0; i < DECK_SIZE; ++i) {
cards.add(Card.forOrdinal(i));
}
}
public void shuffle() {
java.util.Collections.shuffle(cards);
}
public void print() {
for (Card card: cards) {
System.out.print(" '" + card + "' ");
}
System.out.println();
}
}
class Card {
private static final int NUMBER_OF_VALUES = Value.values().length;
private static final int NUMBER_OF_SUITS = Suit.values().length;
public static final int NUMBER_OF_CARD_TYPES =
NUMBER_OF_SUITS*NUMBER_OF_VALUES;
enum Suit {
diamonds, clubs, hearts, spades;
private static Suit forOrdinal(int ordinal) {
return values()[ordinal / NUMBER_OF_VALUES];
}
}
enum Value {
ace, two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king;
private static Value forOrdinal(int ordinal) {
return values()[ordinal];
}
}
final Suit suit;
final Value value;
private Card(Suit suit, Value value) {
this.suit = suit;
this.value = value;
}
public static Card forOrdinal(int ordinal) {
return new Card(Suit.forOrdinal(ordinal),
Value.forOrdinal(ordinal));
}
public String toString() {
return value.toString() + " of " + suit.toString();
}
}
public class Poker {
public static void main(String[] args) {
Deck deck = new Deck();
deck.print();
deck.shuffle();
deck.print();
}
}