I'm trying to clean up code so a selection of values pertaining to a deck of cards rank is an array. I was able to accomplish this with suits, though I can not seem to accomplish it with rank. I simply want to type this out in a way where it will return the same values but not take up so many lines, preferably through an array or linked list.
public String toString() {
return getVal() getSuit();
}
public String getVal() {
int rank = value % 13;
if (rank == 0)
return "2";
else if (rank == 1)
return "3";
else if (rank == 2)
return "4";
else if (rank == 3)
return "5";
else if (rank == 4)
return "6";
else if (rank == 5)
return "7";
else if (rank == 6)
return "8";
else if (rank == 7)
return "9";
else if (rank == 8)
return "10";
else if (rank == 9)
return "J";
else if (rank == 10)
return "Q";
else if (rank == 11)
return "K";
else
return "A";
}
public String getSuit()
{
if (suit.toLowerCase().contains("spade")) {
return "\u2660";
}
else if (suit.toLowerCase().contains("club")) {
return "\u2663";
}
else if (suit.toLowerCase().contains("heart")) {
return "\u2665";
}
else if (suit.toLowerCase().contains("diamond")) {
return "\u2666";
}
return "";
}
CodePudding user response:
For the rank, you can set your string values in a List
with List.of
and use rank
as an index into the list.
private static final List<String> ranks = List.of(
"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A");
Then in the getVal
method:
return ranks.get(rank);
For the suit, you need to map a String
to another String
, using Map.of
.
private static final Map<String, String> suits = Map.of(
"spade", "\u2660", "club", "\u2663", "heart", "\u2665", "diamond", "\u2666");
Then in the getSuit
method:
return suits.getOrDefault(suit.toLowerCase(), "");
The getOrDefault
method returns an alternative value in case the mapping doesn't exist, which appears to be what your code is doing after your if-else if block.
CodePudding user response:
Seems you can do:
if (rank < 9) {
return String.valueOf(rank 2);
}
// handle rest individually