我是Enum类型的新手。我有2个Enum Class,一个是Suits的Rank 1,如下所示
public enum Rank
{
ACE(1), TWO(2), THREE(3),
FOUR(4), FIVE(5), SIX(6),
SEVEN(7), EIGHT(8), NINE(9),
TEN(10), JACK(J), QUEEN(Q),
KING(K);
//private fields
private final int rankValue;
//with constructor passing rankValue
//with method getRank
}
public enum Suit
{
HEARTS("H"),
SPADES("S"),
DIAMONDS("D"),
CLUBS("C");
private final String suitText;
//with constructor and printSuit()
}
在我的主要方法中,我正在弄清楚如何在下面打印它们:
S1 S2 S3 S4 S5 S6 S7 S8 S9 S10 SJ SQ SK
答案 0 :(得分:0)
基本上enum只是另一个java类,有一些细节,但你可以在经典类中大致做同样的事情,所以对于这种情况,例如。以下内容:
public enum CardsEnumWithProps {
HEARTS("H"),
SPADES("S"),
DIAMONDS("D"),
CLUBS("C");
private String stringSign;
private CardsEnumWithProps(String strSign) {
this.stringSign = strSign; //stringSign = strSign
}
public String getStr() {
return this.stringSign;
}
}
然后你可以在枚举值上调用.getStr()
,如:
System.out.println(CardsEnumWithProps.DIAMONDS.getStr());
获取输出D
对于枚举中的每个项目,您可以迭代枚举的.values()
CardsEnumWithProps[] cards = CardsEnumWithProps.values();
for (int i = 0; i < cards.length; i++) {
System.out.println(cards[i].name() + " --- " + cards[i].getStr());
}
你会得到
HEARTS --- H
SPADES --- S
DIAMONDS --- D
CLUBS --- C
答案 1 :(得分:0)
您可以通过以下代码执行此操作:
Rank [] ranks = Rank.values();
Suit [] suits = Suit.values();
for (int i = 0; i < suits.length; i++) {
for (int j = 0; j < ranks.length; j++) {
System.out.print(suits[i].getSuitText + ranks[j].getRank()+"\s");
}
System.out.println("\n");
}