C:\fig20_10>java DeckOfCards Nine of Spades Seven of Hearts Deuce of Diamonds Nine of Hearts Deuce of Hearts Ten of Hearts Seven of Diamonds Queen of Clubs Ten of Spades Nine of Diamonds Seven of Clubs Four of Hearts Ace of Clubs Eight of Diamonds Three of Diamonds Ten of Diamonds Deuce of Spades Queen of Diamonds Five of Diamonds Jack of Clubs Six of Clubs Four of Spades Five of Clubs Eight of Spades Six of Hearts Ace of Hearts Three of Spades Jack of Diamonds Five of Spades Three of Clubs Jack of Hearts Six of Spades Ace of Spades King of Clubs Six of Diamonds Three of Hearts Seven of Spades Four of Clubs Five of Hearts King of Spades Ace of Diamonds Four of Diamonds Jack of Spades King of Hearts Ten of Clubs Queen of Spades Queen of Hearts Eight of Clubs Eight of Hearts Nine of Clubs Deuce of Clubs King of Diamonds
DeckOfCards.java// Fig. 20.10: DeckOfCards.java
// Card shuffling and dealing with Collections method shuffle.
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
// class to represent a Card in a deck of cards
class Card
{
public static enum Face { Ace, Deuce, Three, Four, Five, Six,
Seven, Eight, Nine, Ten, Jack, Queen, King };
public static enum Suit { Clubs, Diamonds, Hearts, Spades };
private final Face face; // face of card
private final Suit suit; // suit of card
// two-argument constructor
public Card( Face cardFace, Suit cardSuit )
{
face = cardFace; // initialize face of card
suit = cardSuit; // initialize suit of card
} // end two-argument Card constructor
// return face of the card
public Face getFace()
{
return face;
} // end method getFace
// return suit of Card
public Suit getSuit()
{
return suit;
} // end method getSuit
// return String representation of Card
public String toString()
{
return String.format( "%s of %s", face, suit );
} // end method toString
} // end class Card
// class DeckOfCards declaration
public class DeckOfCards
{
private List< Card > list; // declare List that will store Cards
// set up deck of Cards and shuffle
public DeckOfCards()
{
Card[] deck = new Card[ 52 ];
int count = 0; // number of cards
// populate deck with Card objects
for ( Card.Suit suit : Card.Suit.values() )
{
for ( Card.Face face : Card.Face.values() )
{
deck[ count ] = new Card( face, suit );
++count;
} // end for
} // end for
list = Arrays.asList( deck ); // get List
Collections.shuffle( list ); // shuffle deck
} // end DeckOfCards constructor
// output deck
public void printCards()
{
// display 52 cards in two columns
for ( int i = 0; i < list.size(); i++ )
System.out.printf( "%-19s%s", list.get( i ),
( ( i + 1 ) % 4 == 0 ) ? "\n" : "" );
} // end method printCards
public static void main( String[] args )
{
DeckOfCards cards = new DeckOfCards();
cards.printCards();
} // end main
} // end class DeckOfCards
Maintained by John Loomis, updated Thu Oct 10 21:06:15 2013