next up previous
Next: Compare cards Up: Assignment 10: Cards and Previous: Reading

The Card class

1.
Create a new Java project called Card and make it an Application. The Card class will define a new type of object that will represent a playing card. It will have two instance variables, both integers, that will represent the rank and suit of the card. Declare two instance variables named rank and suit at the top of the class definition.
2.
Write two constructors for the Card class. One should take no arguments and initialize both instance variables to 0. The other should take the rank and suit as arguments.

3.
Write a toString method for this class. Probably the way you will want to do this is to create two global final arrays of Strings, named ranks and suits:

    public static final String[] suits = 
        { "Clubs", "Diamonds", "Hearts", "Spades" };
    public static final String[] ranks =
        { "narf", "Ace", "2", "3", "4", "5", "6", "7", "8",
          "9", "10", "Jack", "Queen", "King" };

Recall that both global variables and instance variables are declared at the beginning of the class definition, outside of any method, and that you can identify global variables by the presence of the keyword static (and instance variables by its absence).

4.
Within toString you should use the instance variables as indices into the global arrays in order to select the appropriate string for a given rank or suit. For example, if the suit is 0, then the expression suits[suit] generates the String "Clubs". In other words, the value 0 represents the suit Clubs, the value 1 represents the suit Diamonds, etc.

Given all that, why is the first element of the ranks array "narf"?

5.
Write a main method that creates a new card using either constructor, and prints the card using toString.


next up previous
Next: Compare cards Up: Assignment 10: Cards and Previous: Reading
Allen B. Downey
4/21/1998