Thursday, November 18, 2010

Assignment 19 - Deck Of Cards



// Deck of Cards
//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 face 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<> 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 of DeckOfCards constructor

// output deck

public void printCards()
{
//display 52 cards in two colums

for ( int i = 0; i System.out.printf( "%-19s%s", list.get( i ),
( ( i+1 ) %4 == 0 ) ? "\n" : "");
} //end method print cards

public static void main( String[] args )
{
DeckOfCards cards = new DeckOfCards();
cards.printCards();
}//end main
}//end class DeckOfCards

No comments:

Post a Comment