Print Page Print Page

CH12 – The compareTo Method

  1. Complete the previous exercises in Chapter 12 if you haven’t already.
  2. Add a new method named equals and a new method named compareTo.
  public boolean equals(Card that){
    return this.rank == that.rank && this.getSuit() == that.getSuit();
  }

  public int compareTo(Card that){
    int retVal = 0;
    if(this.suit < that.getSuit()) retVal = -1; else if(this.suit > that.getSuit()) retVal = 1;
    else if(this.rank < that.getRank()) retVal = -1; else if(this.rank > that.getRank()) retVal = 1;
    return retVal;
  }

Notice that the compareTo presented here is different than that presented in the book. However, the logic is the same. Logical evaluations can usually be performed multiple ways. My preference is that a method only have one exit point rather than multiple return statements, so I modified the compareTo method.

  1. Save Card.java, open CardDriver.java, and add the following code to the main method.
int opponentRank = Integer.parseInt(args[0]);
int opponentSuit = Integer.parseInt(args[1]);
Card opponentCard = new Card(opponentRank, opponentSuit);
System.out.println(opponentCard.toString());
System.out.println(myCard.equals(opponentCard));
System.out.println(myCard.compareTo(opponentCard));
  1. Compile CardDriver.java and run the program several times. Pass different command-line parameters each time you run the program.
$ javac CardDriver.java
$ java CardDriver 3 1
1
2
Ace of Hearts
3 of Diamonds
false
1
$ java CardDriver 3 3
1
2
Ace of Hearts
3 of Spades
false
-1
$ java CardDriver 1 2
1
2
Ace of Hearts
Ace of Hearts
true
0