Lab 1380 - Cards


Card games are implemented well with objects. A card can be an object, with values for rank and suit and methods to print a card or to compare two cards. A deck is an object, containing an array of card objects. Similarly, a hand is a grouping of cards, five for the game of Poker, thirteen for many other games. In this project, you will create and test many interacting classes.

This project is accomplished in steps. Each step is more advanced than the steps before it. You should accomplish the steps in order.

 Step 1 

Create a Card class with a constructor that has suit and rank as arguments. Also provide a public String toString() method. Here is a simple test program that will output "2 of Clubs" and "Ace of Spades".

public class TestCard
   public static void main( String args[] )
        Card c1 = new Card( 0, 1 );
        Card c2 = new Card( 3, 13 );

 Step 2 

Add a method public int compareTo(Object other) that returns 1 if this card is "higher" than c2, -1 if it is lower, and 0 if they have the same value. First compare rank of cards, 2 through Ace with Ace highest. If rank is the same, then compare suits in order of clubs, diamonds, hearts and spades with spades highest. By doing this, you have implemented the Comparable interface.

 Step 3 

Create a new class, Deck, that holds 52 cards. Use an ArrayList to hold the Card objects. To verify that you have a proper deck, write and test a method printDeck() that displays all the cards.

 Step 4 

Complete the Deck class. The methods you should add to include

    public boolean empty () true if deck empty
    public int numCards () how many cards in deck
    public Card dealCard ()   deal a card from the deck  
    public void shuffle () shuffle the deck

Test this by creating a deck, displaying it, shuffling, displaying it again, dealing two hands of five cards, verifying there are 42 cards left in the deck, and displaying the two hands dealt.

 Step 5 

The concept of a hand of cards naturally belongs in an object. Write appropriate code for, then construct two objects of type Hand, each having five cards. As you get cards from the Deck class and insert them into the Hand class, sort them using an insertion sort, one incoming card at a time. Display each hand using a printHand() method in class Hand.


This is a revison of an earlier project of the same name that differs in several useful ways. It uses ArrayLists instead of normal arrays. It implements the Comparable inteface and an Insertion Sort so cards can be compared and consequently hands can be sorted, evaluated and compared. Thanks to Elisse Ghitelman at Newton North HS in Newton, Mass. for her suggestions for these improvements.

Copyright © 2010 by Asylum Computer Services LLC Return to CS Labs