Deck.java


Below is the syntax highlighted version of Deck.java from §3.5 Inheritance.


/******************************************************************************
 *  Compilation:  javac Deck.java
 *  Execution:    java -cp .:cards.jar Player
 *  Dependencies: Card.java
 *
 *  Implement a deck of cards.
 *
 ******************************************************************************/

public class Deck {
    final static int DECK_SIZE = 52;

    private Card[] cards;         // the cards  - cards[0] is bottom of deck
    private int N;                // number of cards

    public Deck()  {
        N = DECK_SIZE;
        cards = new Card[N];
        for (int i = 0; i < N; i++)
            cards[N - i - 1] = new Card(i, i + ".gif", "b.gif");
    }

    public Card dealFrom()   { return cards[--N]; }
    public boolean isEmpty() { return (N == 0);   }

    // shuffles cards
    public void shuffle() {
        for (int i = 0; i < N; i++) {
            int r = (int) (Math.random() * (i+1));   // between 0 and i
            Card swap = cards[i];
            cards[i]  = cards[r];
            cards[r]  = swap;
        }
    }

    // return string representation
    public String toString() {
        String s = "Deck  ";
        for (int i = N - 1; i >= 0; i--)
            s += cards[i] + " ";
        return s;
    }


   // test client
   public static void main(String[] args) {
      Deck deck = new Deck();
      StdOut.println(deck);
      deck.shuffle();
      StdOut.println(deck);
   }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:27:11 EDT 2022.