import java.util.ArrayList; /** * A DeckOfCards object represents a standard deck of 52 playing cards. * * @author Dave Reed * @version 11/25/05 */ public class DeckOfCards { private ArrayList deck; /** * Creates a deck of 52 cards in order. */ public DeckOfCards() { deck = new ArrayList(); String suits = "SHDC"; String ranks = "23456789TJQKA"; for (int s = 0; s < suits.length(); s++) { for (int r = 0; r < ranks.length(); r++) { Card c = new Card(ranks.charAt(r), suits.charAt(s)); deck.add(c); } } } /** * Shuffles the deck so that the locations of the cards are random. */ public void shuffle() { for (int c = deck.size()-1; c > 0; c--) { int swapIndex = (int)(Math.random()*(c+1)); Card tempCard = (Card)deck.get(c); deck.set(c, deck.get(swapIndex)); deck.set(swapIndex, tempCard); } } /** * Deals a card from the top of the deck, removing it from the deck. * @return the card that was at the top (i.e., end of the ArrayList) */ public Card dealCard() { return deck.remove(deck.size()-1); } /** * Adds a card to the bottom of the deck. * @param c the card to be added to the bottom (i.e., the beginning of the ArrayList) */ public void addCard(Card c) { deck.add(0, c); } /** * @return the number of cards remaining in the deck */ public int cardsRemaining() { return deck.size(); } /** * @return a String representation of the deck */ public String toString() { return deck.toString(); } }