/** Here we define the Deck class, which will be an array of 52 shuffled * Card objects. When we make a new project, we can include the same or * similar Card.java file as we did with other card games. */ import java.util.*; public class Deck { private Card [] deck; private int howManyDealt; /** The default constructor will initialize the deck of 52 cards and * also set the number of cards already dealt to 0. */ public Deck() { Random generator = new Random(); // Step 1. Make an array of shuffled integers 1-52, called "decknum". // decknum is a temporary array that is the heart of how to shuffle: // For each of the 52 positions in the array, we need to insert a unique // random number. To make sure it's unique, we look back over the earlier // portion of the decknum array to check we haven't used this number // already. int [] decknum = new int [52]; deck = new Card [52]; for (int i = 0; i < 52; ++i) { int num = generator.nextInt(52) + 1; while (isInArray(decknum, num)) num = generator.nextInt(52) + 1; decknum[i] = num; } // Step 2. Create each card object and put it in the deck array. // At first it may seem confusing that this loop index i and the // deck's array indices are numbered 0-51 (which we have no choice // about), while the numbers we put into the array are in the range // 1-52. I found it more intuitive to number the cards 1-52. // We could have written these 2 for loops (above and below) as a single // loop (because you don't need to wait for all 52 unique numbers to be // determined before making the correspondence from integers to cards), // but for clarity I split the looping into 2 steps here. for (int i = 0; i < 52; ++i) { Card c = new Card (decknum[i]); deck[i] = c; } howManyDealt = 0; } /** isInArray() will determine if we have already put this number x into * the array a. */ public boolean isInArray(int [] a, int x) { boolean found = false; for (int i = 0; i < a.length; ++i) if (a[i] == x) found = true; return found; } /** toString() will print the cards, 13 per line. Because the Card * toString() is set up to print "queen of diamonds" I've added a new * function there called shortForm() so it will only print Q-d, which * will make it much easier to visualize the entire deck. */ public String toString() { String display = new String(); for (int i = 0; i < 52; ++i) { // insert a newline every 13 cards -- including a newline at beginning if (i % 13 == 0) display += "\n"; display += deck[i].shortForm() + " "; } // and a newline at the end display += "\n"; return display; } /** Here we grab the next card out of the deck. We need to increment * howManyDealt so that the next time we're here we are getting the * next card. * This is a simple implementation. To make it more realistic, we * could reshuffle the deck after drawing the 52nd card. (If we didn't * want to reshuffle the cards we could just reset howManyDealt to 0. */ public Card getNextCard() { Card c = new Card(deck[howManyDealt]); ++howManyDealt; return c; } }