我正在尝试创建一个创建数组并用自定义对象填充数组的构造函数。此阵列将代表一张卡片。
public class DeckOfCards {
public static Card[] deck = new Card[52];
//constructor
DeckOfCards(){
Card[] deck = new Card[52];
deck[0]=new Card("Ace","Clubs"); deck[1]=new Card("Two","Clubs");
deck[2]=new Card("Three","Clubs");..(ect)...deck[49]=new
Card("Jack","Diamonds");
deck[50]=new Card("Queen","Diamonds"); deck[51]=new Card("King","Diamonds");
}
我觉得这个构造函数应该创建一个数组并用卡片对象填充它,但它不识别从deckofcards((((阵列实例化的任何对象。
您在构造函数内再次声明甲板。我会以这种方式初始化甲板。通过两个阵列迭代,最简单的一个。
DeckOfCards(){
suit = ['Hearts','Diamonds','Clubs','Spades'];
number=['Ace','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King'];
for (int i=0;i<4;i++){
for (int j=0;j<13;j++){
deck[i+j]=new Card(number[j],suit[i]);
}
}
}
您有一个范围问题,因为您再次声明
Card[] deck = new Card[52];
在构造函数内部,没有影响全局成员,而是使用甲板对象....(顺便说一句,不需要静态对象...(
DeckOfCards(){
deck[0]=new Card("Ace","Clubs"); deck[1]=new Card("Two","Clubs");
deck[2]=new Card("Three","Clubs");..(ect.).deck[49]=new
Card("Jack","Diamonds");
deck[50]=new Card("Queen","Diamonds"); deck[51]=new Card("King","Diamonds");
}
首先,您无需在构造函数中再次初始化deck
。只需使用您定义的类级变量即可。
第二,deck
不应是static
,因此请删除该单词。
第三,将构造函数公开。
,最后但并非最不重要的一点,您可能应该以更聪明的方式初始化甲板。
public class DeckOfCards {
public Card[] deck = new Card[52];
//constructor
public DeckOfCards(){
String[] numbers = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
String[] suits = { "Spades", "Clubs", "Diamonds", "Hearts" };
int i = 0;
for (String suit: suits) {
for (String number: numbers) {
deck[i] = new Card(number, suit);
i++;
}
}
}
}
删除该行,它会没关系:
卡[]甲板=新卡[52];