This is a programming exercise from Chapter 6 of The Art and Science of Java.
Implement a new class called Card that includes the following entries:
• Named constants for the four suits (CLUBS, DIAMONDS, HEARTS, SPADES)
and the four ranks that are traditionally represented in words (ACE,
JACK, QUEEN, KING). The values of the rank constants should be 1, 11,
12, and 13, respectively.• A constructor that takes a rank and a suit and returns a Card with
those values.• Getter methods named getRank and getSuit to retrieve the rank and suit
components of a card.• An implementation of the toString method that returns the complete
name of the card as in exercise 1. Remember that you can use the +
operator to connect the different parts of the string together, as
shown in the toString implementation for the Rational class in Figure
6-9.
My code:
/*
* File: Card.java
*
*/
public class Card {
/* Named Constants for ranks*/
public static final int ACE = 1;
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
/* Named Constants for suits*/
public static final int CLUBS = 1;
public static final int DIAMONDS = 2;
public static final int HEARTS = 3;
public static final int SPADES = 4;
public Card(int rank, int suit) {
cardRank = rank;
cardSuit = suit;
}
public int getRank() {
return cardRank;
}
public int getSuit() {
return cardSuit;
}
public String toString() {
return (toRankName() + " of " + toSuitName());
}
private String toRankName() {
switch (cardRank) {
case 1:
return ("Ace");
case 11:
return ("Jack");
case 12:
return ("Queen");
case 13:
return ("King");
default:
return ("" + cardRank);
}
}
private String toSuitName() {
switch (cardSuit) {
case 1:
return ("Clubs");
case 2:
return ("Diamonds");
case 3:
return ("Hearts");
case 4:
return ("Spades");
default:
return ("Invalid");
}
}
private int cardRank;
private int cardSuit;
}
The part that I am unsure of is “Getter methods named getRank and getSuit to retrieve the rank and suit components of a card.”
Is the question asking me to return the int value or a String value(Name)?
This is the first time I’ve implemented a class. Apart from the lack of JavaDoc comments, is there anything else wrong with my code?
edit:
Many thanks to everyone that replied!
Your code looks spot-on as far as the requirements are concerned.
The only suggestion I have is to use the named constants in the two
switchstatements:The requirements seem a little odd in that they force you to use named constants where enums would arguably be more appropriate.