Java枚举,整数和字符串一起定义?

2022-09-04 07:37:00

我想一起定义字符串和整数,但它给出了错误。

public class Card {
    Rank rank;
    Suit suit;
    public Card(Rank rank, Suit suit){
        this.rank=rank;
        this.suit=suit;
    }
    public enum Rank { Ace, 9, Queen, King } //and other suits
}

该错误是令牌 9 上的语法错误,请删除此令牌。


答案 1

在Java中声明枚举时,这些不是字符串和整数。这些是枚举的实际对象。{ Ace, 9, Queen, King }

您可以执行以下操作:

 public enum Rank { 
     Ace(13), 
     Nine(8),
     //etc
     ;

     private int rank;

     Rank(int rank) {
         this.rank = rank;
     }

     public int getRank() { 
         return rank;
     }
 }

答案 2

里面的东西是标识符,是将要创建的静态最终(常量)对象的名称。因此,不能使用 int 来命名对象。enum

enums 允许您为每个条目放置字段:

public static enum Suit {HEART,DIAMOND,SPADE,CLUB}

public static enum Cards {
    ACE_OF_HEART(Suit.HEART,14), QUEEN_OF_SPADE(Suit.SPADE,13) /* etc etc*/;

    private final Suit mSuit;
    private final int mRank;

    private Cards(Suit suit, int rank) {
        assert rank >= 2 && rank <= 14;
        mSuit = suit;
        mRank = rank;
    }

    public Suit getSuit() {
        return mSuit;
    }

    public int getRank() {
        return mRank;
    }
}

你真的不想以这种方式对所有52张卡进行编码。您可以通过另一种方式对其进行建模:

套房:

public static enum Suit { SPADE, HEART, DIAMOND, CLUB};

将一些流行的等级作为命名常量的类:

public class Card{

  public static final int ACE = 14;
  public static final int QUEEN = 13;
  public static final int KING = 12;
  public static final int JACK = 11;

  private final int mRank;
  private final Suite mSuit;

  public Card(Suite s, int r){
    this.mSuit = s;

    if(r < 2 || r > 14){
      throw new IllegalArgumentException("No such card with rank: "+r);
    }    

    this.mRank = r;
  }

  public Suit getSuit() {
        return mSuit;
    }

    public int getRank() {
        return mRank;
    }
}