用循环枚举枚举实例

Aar*_*ang 5 java enums loops coding-style syntactic-sugar

场景:
我想要一个包含标准牌组中所有扑克牌的枚举.对于这个例子,忽略这些笑话.

写作

enum Cards {
    SPADE_1(0, 1),
    SPADE_2(0, 2),
    etc.
Run Code Online (Sandbox Code Playgroud)

感觉不对.

我希望能够做到这样的事情

enum Card {
    for (int suit=0; suit<4; suit++) {
        for (int face=1; face<13; face++) {
            new Card(suit, face);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经考虑将卡片定义为包含西装和脸部领域的类,其中西装和脸部本身就是枚举.然而,在其他情况下(例如具有红色和黑色的套装的笑话),这将允许创建无效的卡对象(即,钻石的小丑或红色10).

自我回答:
显然我没有足够的代表来回答我自己的问题.

I'm not sure if it's considered good form to answer my own question, but @Paul just gave me a brainwave.

Declare Card to have a private constructor, and use a
    static Card getCard(suit, face)
method to validate combinations before returning them.

dku*_*mar 1

我不认为可以使用它来完成,enum但我们可以使用implement classas 来完成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++;
            }
        }
      }
}
Run Code Online (Sandbox Code Playgroud)

编辑: 设置counter卡的。早些时候,它会抛出NullPointerException索引超过 15 的情况。

用途:

System.out.println("face of the card:"+Card.cards[10].getFace());
System.out.println("suit of the card:"+Card.cards[10].getSuit());
Run Code Online (Sandbox Code Playgroud)

输出:

face of the card:7
suit of the card:3
Run Code Online (Sandbox Code Playgroud)