The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


The printCard Method

When you create a new class, the first step is usually to declare the instance variables and write constructors. The second step is often to write the standard methods that every object should have, including one that prints the object, and one or two that compare objects. I will start with printCard.

In order to print Card objects in a way that humans can read easily, we want to map the integer codes onto words. A natural way to do that is with an array of Strings. You can create an array of Strings the same way you create an array of primitive types:

    String[] suits = new String [4];

Then we can set the values of the elements of the array.

    suits[0] = "Clubs";
    suits[1] = "Diamonds";
    suits[2] = "Hearts";
    suits[3] = "Spades";

Creating an array and initializing the elements is such a common operation that Java provides a special syntax for it:

    String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };

The effect of this statement is identical to that of the separate declaration, allocation, and assignment. A state diagram of this array might look like:

The elements of the array are references to the Strings, rather than Strings themselves. This is true of all arrays of objects, as I will discuss in more detail later. For now, all we need is another array of Strings to decode the ranks:

  String[] ranks = { "narf", "Ace", "2", "3", "4", "5", "6",
    "7", "8", "9", "10", "Jack", "Queen", "King" };

The reason for the "narf" is to act as a place-keeper for the zeroeth element of the array, which will never be used. The only valid ranks are 1--13. This wasted entry is not necessary, of course. We could have started at 0, as usual, but it is best to encode 2 as 2, and 3 as 3, etc.

Using these arrays, we can select the appropriate Strings by using the suit and rank as indices. In the method printCard,

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

    System.out.println (ranks[c.rank] + " of " + suits[c.suit]);
  }

the expression suits[c.suit] means "use the instance variable suit from the object c as an index into the array named suits, and select the appropriate string." The output of this code

    Card card = new Card (1, 11);
    printCard (card);

is Jack of Diamonds.



Last Update: 2011-01-24