gpt4 book ai didi

java - 如何将对象添加到枚举定义的类中?

转载 作者:行者123 更新时间:2023-11-29 03:05:54 29 4
gpt4 key购买 nike

我正在尝试遵循 Oracle 文档中的这段代码,它向您展示了如何使用 Java ENUMS。但是,我试图在最后的 protoDeck 中添加一个“ clown ”因为每副 52 张牌可以包含一张额外的“ clown ”或“ clown ”牌。我无法将 CLOWN 添加到 SUIT 或 RANK,因为它们都不是。

我尝试创建一个新的 enum作为

   public enum Clown {Clown} 

并试图将其放入 protoDeck 但它不起作用

    public class Card {
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}

public Rank rank() { return rank; }
public Suit suit() { return suit; }
public String toString() { return rank + " of " + suit; }

private static final List<Card> protoDeck = new ArrayList<Card>();

// Initialize prototype deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
protoDeck.add(new Card(rank, suit));
}

public static ArrayList<Card> newDeck() {
return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
}
}

最佳答案

Card变成一个接口(interface)。

您可以将 Clown 链接到与其他卡片相同的组中,只要让它在这些情况下也表现得适当即可。所以你会有类似的东西:

public interface Card {
Rank getRank();
Suit getSuit();
}
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE, OTHER }
public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES, NONE }
public class RegularCard implements Card {
private RegularCard(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}

public Rank getRank() { return rank; }
public Suit getSuit() { return suit; }
}
public enum MiscellaneousCards implements Card {
CLOWN, JOKER;

// etc.
}

关于java - 如何将对象添加到枚举定义的类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32195507/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com