所以我正在用 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上看到完整的项目。