【发布时间】:2019-06-20 16:12:09
【问题描述】:
我正在为学校写作业。 我正在制作一副简化的纸牌,您可以选择花色的数量和每个花色的纸牌数量。 (西装和等级)。我有一个创建单张卡片的 Card 类和一个创建一副卡片(一副卡片对象)的 DeckOfCards 类。我试图将卡片放入 ArrayList(在 DeckOfCards 构造函数内),但每次它只是创建对最近创建的卡片的引用。我花了几个小时试图弄清楚,但在任何搜索中都找不到答案。
public class DeckOfCards
{
private int counter = 0;
private ArrayList<Card> cardList = new ArrayList<>();
public DeckOfCards(int rank, int suit)
{
for (int x = 0; x < suit; x++) // x is suit
{
for (int y = 0; y < rank; y++) // y is rank
{
cardList.add(counter, new Card(x, y));
counter++; // counter is position in ArrayList / deck
}
}
}
public String dealCard(int numOfCards)
{
// returns the card (numOfCards)
return cardList.get(numOfCards).toString();
}
}
/* Card Class and Constructor
public class Card
{
private static int SUIT;
private static int RANK;
public Card(int suit, int rank)
{
this.SUIT = suit;
this.RANK = rank;
}
public String toString()
{
return ("S"+ SUIT + "R" + RANK);
}
}
Depending on the rank and suit the output should be
S1R1
S1R2
S1R3
.
.
.
S4R1
S4R2
S4R3
But the out put is always the last card created
S4R3
【问题讨论】:
-
因为
Card类中的字段是静态的。所以它不是引用添加到卡片组中的最后一张卡片,而是您所有卡片的字段值都相同,因为您将它们声明为static -
天哪,我真是太傻了。谢谢!