Java Reference
In-Depth Information
Your
Card
class has two data members that are both enumeration types. One defines the suit and the other
defines the face value of the card.
You will undoubtedly need to display a card, so you need a
String
representation of a
Card
object. The
toString()
method can do this for you:
public class Card {
@Override
public String toString() {
return rank + " of " + suit;
}
// Other members as before...
}
Directory "TryDeal"
The
String
representation of an
enum
constant is the name you assign to the constant, so the
String
representation of a
Card
object with the
suit
value as
CLUBS
and the
rank
value as
FOUR
is
"FOUR of
CLUBS"
.
In general, you probably want to compare cards, so you could also make the
Card
class implement the
Comparable<>
interface:
public class Card implements Comparable<Card> {
// Compare two cards
public int compareTo(Card card) {
if(suit.equals(card.suit)) {
// First
compare suits
if(rank.equals(card.rank)) {
// So check
face values
return 0;
// They are
equal
}
return rank.compareTo(card.rank) < 0 ? -1 : 1;
} else {
// Suits are
different
return suit.compareTo(card.suit) < 0 ? -1 : 1; // Sequence is
C<D<H<S
}
}
// Other members as before...