这是一个名为 Card 的类,我们在其中为每张卡片创建一个映射器。请注意,它只是将 0 用于小丑,但在 for 循环中,我从 1 开始不包括它,如输出所示。希望这会有所帮助!
import java.util.Arrays;
import java.util.HashMap;
public class Card {
public int cardV;
public String cardS;
private HashMap<Integer, String> cardMapper;
Card(int newCardValue){
//create our mapper first
cardMapper = createCardMapping();
cardV = newCardValue;
//once the mapper is created we can now figure out the string of our card
cardS = FindCardStringRep(cardV);
}
private String FindCardStringRep(int key)
{
String cardString = "Card Doesn't Exist";
if(cardMapper.containsKey(key))
{
cardString = cardMapper.get(key);
}
return cardString;
}
public HashMap<Integer, String> createCardMapping()
{
HashMap<Integer, String> mapper = new HashMap<>();
String[] cardNames = {"joker", "ace", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "jack", "queen", "king"};
//go through and create a mapping of the indices of cardNames to the String representations
//Note 0 = joker, ace = 1, two = 2 and so on
//we start at 1 so we ignore the joker anyways
for(int intVal = 1; intVal < cardNames.length; intVal++)
mapper.put(intVal, cardNames[intVal]);
return mapper;
}
}
然后在 main 方法中你可以像下面这样
for(int i = 0; i < 20; i++)
{
Card card = new Card(i);
System.out.println("Card " + card.cardV + " is a " + card.cardS);
}
输出如下:
Card 0 is a Card Doesn't Exist
Card 1 is a ace
Card 2 is a two
Card 3 is a three
Card 4 is a four
Card 5 is a five
Card 6 is a six
Card 7 is a seven
Card 8 is a eight
Card 9 is a nine
Card 10 is a ten
Card 11 is a jack
Card 12 is a queen
Card 13 is a king
Card 14 is a Card Doesn't Exist
Card 15 is a Card Doesn't Exist
Card 16 is a Card Doesn't Exist
Card 17 is a Card Doesn't Exist
Card 18 is a Card Doesn't Exist
Card 19 is a Card Doesn't Exist