Java 使用循环枚举枚举枚举实例
场景:Java 使用循环枚举枚举枚举实例,java,loops,coding-style,enums,syntactic-sugar,Java,Loops,Coding Style,Enums,Syntactic Sugar,场景: 我想要一个枚举,包含标准牌组中的所有扑克牌。对于这个例子,忽略小丑 书写 enum Cards { SPADE_1(0, 1), SPADE_2(0, 2), etc. 感觉不对 我希望能做这样的事情 enum Card { for (int suit=0; suit<4; suit++) { for (int face=1; face<13; face++) { new Card(suit, face
我想要一个枚举,包含标准牌组中的所有扑克牌。对于这个例子,忽略小丑 书写
enum Cards {
SPADE_1(0, 1),
SPADE_2(0, 2),
etc.
感觉不对
我希望能做这样的事情
enum Card {
for (int suit=0; suit<4; suit++) {
for (int face=1; face<13; face++) {
new Card(suit, face);
}
}
}
枚举卡{
对于(int suit=0;suit我认为使用enum
无法实现,但我们可以实现类作为enum
。您可以执行以下操作
实施:
public class Card {
private int suit;
private int face;
private Card(int suit, int face){
this.suit = suit;
this.face = face;
}
public int getSuit(){
return this.suit;
}
public int getFace(){
return this.face;
}
public static Card[] cards = new Card[52];
static{
int counter =0;
for (int i=0; i<4; i++) {
for (int j=0; j<13; j++) {
cards[counter] = new Card(i, j);
counter++;
}
}
}
}
System.out.println("face of the card:"+Card.cards[10].getFace());
System.out.println("suit of the card:"+Card.cards[10].getSuit());
face of the card:7
suit of the card:3
输出:
public class Card {
private int suit;
private int face;
private Card(int suit, int face){
this.suit = suit;
this.face = face;
}
public int getSuit(){
return this.suit;
}
public int getFace(){
return this.face;
}
public static Card[] cards = new Card[52];
static{
int counter =0;
for (int i=0; i<4; i++) {
for (int j=0; j<13; j++) {
cards[counter] = new Card(i, j);
counter++;
}
}
}
}
System.out.println("face of the card:"+Card.cards[10].getFace());
System.out.println("suit of the card:"+Card.cards[10].getSuit());
face of the card:7
suit of the card:3
我会说做两个枚举:一个用于每个面,另一个用于每个卡。因此在卡枚举中,每个枚举都有两个属性:卡的数量(如果不想使用普通数字,可以再做一个枚举),和face,这是face enum的一个实例。这应该可以解决问题。我对等级、西装和卡片使用了一个enum,似乎效果很好。代码见下面的答案:也许一个enum
不是你想要的。你真的需要将这3个俱乐部称为clubs\u 3吗?是的,绝对——私有构造函数,单独的enums用于西服和面部。我仍然需要手动枚举所有52张卡片,这是我试图避免的。我想减少源数量以便于理解等。我会使用enums用于西服和面部,但我认为公共只读集合与get(FACE,SUIT)方法相结合是正确的方法。你可以采用任何一种方法(使用enum或普通类制作卡片)查看方法:公共静态卡片实例(等级,套装)…在链接到的手指受伤的手册中,这正是我试图避免的