0

所以我正在用 Java 编写二十一点,我已经将我的西装和排名值存储在枚举中

public enum Suit
{
   spades, hearts, clubs, diamonds
}



public enum Rank
{
    two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace
}

我有一个甲板课程,里面有一堆“卡片”。卡片包含 Suit 和 Rank 字段。

public class Card
{
    static Suit suit;
    static Rank rank;


    Card(Suit suit, Rank rank)  
    {

    this.suit = suit;
    this.rank = rank;

    }


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

    //getters and setters ommitted
}

Deck 中的构造函数应该遍历每个花色和等级,并将这些作为参数传递以创建一副 52 张牌,但它似乎停留在每张牌的最后一个值上,我最终得到 52 个“梅花 A” . 我不明白为什么,由于西装和等级似乎打印正确,似乎只是当它们作为参数传递给 add() 时,它们行为不端。

public class Deck
{
    static Stack<Card> d = new Stack<Card>();

    Deck()
    {
    if (!d.isEmpty())
    {
        clear(); //Empties the stack if constructor is called again
    }

    for (Suit suit : Suit.values())
    {
        for (Rank rank : Rank.values())
        {
        //System.out.println(suit + " " + rank);
        //This seems to print the right values

        add(new Card(suit, rank)); //These are stuck on 'clubs' and 'ace'
        }
    }

    System.out.println(d);

    shuffle(); //Method which shuffles the deck

    }

    public static void add(Card c)
    {
    d.addElement(c);
    }

    //shuffle(), clear() and other methods omitted
}

如果有帮助,可以在github上看到完整的项目。

4

3 回答 3

4

您在卡片中的花色和等级字段不应该是静态的!

你的 Deck 领域也不应该!

静态字段是每个类的,因此您的 Card 构造函数每次调用时都会覆盖相同的值。

于 2012-12-18T02:43:24.030 回答
0

这是不正常的。你可以DeckStack.

public class Deck
{
    static Stack<Card> d = new Stack<Card>();

在这种情况下,您可以add直接在.clearshuffleDeck

public class Deck extends Stack<Card> {
    //add, clear are already there from Stack
}
于 2012-12-18T02:28:03.783 回答
0

您可以在枚举上调用 values() 方法。

for ((Rank rank : Rank.values()) {
  // do what you want
}

这个 values() 方法由编译器隐式声明。所以它没有在 Enum 文档中列出。

于 2016-06-23T06:53:45.807 回答