Rank of Cards in a Game
class, java
Solution
Enums are your friend. As you've discovered, `int`s are not appropriate, because they work for only some of the cases (ace through ten), and there's nothing stopping your user from giving an illegal value (negative or greater than 13). Enums can both enforce correct values, and also can also easily associate any numeric value you like.
public enum CardRank {
ACE(1),
TWO(2),
THREE(3),
...
TEN(10),
JACK(10),
QUEEN(10),
KING(10);
private final int value;
CardRank(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Using this, you'd set the rank with
public void Card(CardRank rank, CardSuit suit) {
this.rank = rank;
this.suit = suit;
}
public int getRankValue() {
return rank.getValue();
}
Another benefit of enums is much clearer, self-documenting functions. If the parameters are both `int`s, then, by just looking at the signature's types, it's not clear which is the rank and which is the suit. With enums, it's a non-issue.
I'll leave `CardSuit` as an exercise :)
More info:
- http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
- What's the use of "enum" in Java?
- What are enums and why are they useful?
- Java class card enum example. REVISED
Problem
I'm a beginner Java student. So any help will be much appreciated! I've designed a class Cards and class Deck that I will use in a game that I've created. So far, my game seems to be working very well, but the problem I have lies in my Cards class. I'd like to utilize my getRank() method as a way to accumulate points for the cards a player has (regardless of suit). For example, if they draw a 2 of Diamonds, it will be worth 2 points, 3 of hearts 3 points...ect. I've created a `String[]` called `ranks` to try to do this, and I think that's what it does. However, I'd like all face cards (like king, queen...) to have a value of 10. But not all these cards lie at index 10 in my array. Could I have some guidance as to how to go about adjusting this? Thank you in advance. ``` int rank; int suit; String[]ranks = { " "," ", " " } //all 13 ranks from Ace to King String[]suits = { " ", " ", " "} //all ranks public Card(int rank, int suit){ this.rank = rank; this.suit = suit; } public void setRank(int rank){ this.rank = rank; } public int getRank(){ return rank; } //more code for suits public String toString(){ return ranks[rank]+" of "+suits[suit]; } ```