Print Page Print Page

CH12 – Card to String

  1. If you didn’t complete the previous tutorial, do so now.
  2. Open Card.java and add a toString method.
  public String toString(){
    String[] ranks = {null,"Ace","2","3","4","5","6","7","8","9",
       "10","Jack","Queen","King"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    String s = ranks[this.rank] + " of " + suits[this.suit];
    return s;
  }
  1. Open CardDriver.java and add a line to the main method that calls the toString method and prints it to the console.
System.out.println(myCard.toString());
  1. Compile and run the program.
$ javac CardDriver.java
$ java CardDriver
1
2
Ace of Hearts

The complete Card class should appear as follows.

public class Card {
  private int rank;
  private int suit;

  public int getRank(){
    return this.rank;
  }

  public int getSuit(){
    return this.suit;
  }

  public Card(int rank, int suit){
    this.rank = rank;
    this.suit = suit;
  }

  public String toString(){
    String[] ranks = {null,"Ace","2","3","4","5","6","7","8","9",
       "10","Jack","Queen","King"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    String s = ranks[this.rank] + " of " + suits[this.suit];
    return s;
  }
}

The complete CardDriver class should appear as follows.

public class CardDriver {
  public static void main(String[] args){
    Card myCard = new Card(1,2);
    System.out.println(myCard.getRank());
    System.out.println(myCard.getSuit());
    System.out.println(myCard.toString());
  }
}