I have the following enum which represents a CardRank
public enum CardRank
{
DEUCE('2'), TREY('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'),
EIGHT('8'), NINE('9'), TEN('T'), JACK('J'), QUEEN('Q'), KING('K'),
ACE('A');
private char symbol;
private CardRank(char symbol)
{
this.symbol = symbol;
}
public char getSymbol()
{
return this.symbol;
}
}
The CardRank
is represented in ascending order. I need to compare the ranks in order to know which rank is greater than the other. I can use >
operator with the numerical values but not with the char values.
// this will print out TRUE for all numerical values compared
// but FALSE for the chars
if (card.getRank().getSymbol() > anotherCard.getRank().getSymbol()) {
System.out.println("true");
} else {
System.out.println("false");
}
Any ideas?
if (card.getRank().compareTo(anotherCard.getRank()) > 0)
is what you need.
You may alwo use the ordinal:
if (card.getRank().ordinal() > anotherCard.getRank().ordinal())
Enums have a natural ordering defined by their ordinal. And the ordinal of an enum is attributed based on its position in the declaration. So DEUCE has ordinal 0, TREY has ordinal 1, etc.
Consider using a Comparator for this. It can be a public static inner class if you desire:
import java.util.Comparator;
public enum CardRank implements Comparable<CardRank> {
DEUCE('2'), TREY('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'), EIGHT('8'), NINE(
'9'), TEN('T'), JACK('J'), QUEEN('Q'), KING('K'), ACE('A');
private char symbol;
private static CardRankComparator cardRankComparator = new CardRankComparator();
private CardRank(char symbol) {
this.symbol = symbol;
}
public char getSymbol() {
return this.symbol;
}
public int compareRank(CardRank otherCardRank) {
return cardRankComparator.compare(this, otherCardRank);
}
// public so that this can be used for sorting if need be
public static class CardRankComparator implements Comparator<CardRank> {
private static final String RANKS = "23456789TJQKA";
@Override
public int compare(CardRank cr1, CardRank cr2) {
int rank1 = RANKS.indexOf(String.valueOf(cr1.getSymbol()));
int rank2 = RANKS.indexOf(String.valueOf(cr2.getSymbol()));
return rank1 - rank2;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With