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];
}
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.Using this, you'd set the rank with
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:
You could restructure your Card class to also have a 'value' or equivalent parameter used to store the point value of each card. However, point value is more of a piece of game logic. Maybe give your game a method
getValue(Card c)
that converts a card's rank into a value based upon your logic. The method could look like this