我正在尝试用Java创建一副卡片。
package cardgame;
public class CardGame {
String[] numberList = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
String[] suitList = {"Hearts", "Diamonds", "Clubs", "Spades"};
Card[] deck = new Card[52];
public static void main(String[] args) {
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 13; j++) {
deck.add(Card(numberList[j], suitList[i]));
}
}
}
}
不幸的是这种添加卡片的方法不起作用,有没有人有任何建议?我收到以下错误:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Array.add
at cardgame.CardGame.main(CardGame.java:12)
我主要是在python中进行编码所以我不确定我的语法是否正确
我的卡片构造函数如下:
package cardgame;
public class Card {
private String number;
private String suit;
public Card(String number, String suit) {
this.number = number;
this.suit = suit;
}
答案 0 :(得分:1)
Java数组没有“添加”方法。它们不是对象。你想说
deck[i*13+j] = new Card(numberList[j], suitList[i]);
假设您已使用该构造函数在某处定义了卡类。
答案 1 :(得分:0)
您必须通过调用“new”
创建对象new Card(numberList[j], suitList[i])
此外,如果您使用数组,则无法使用add。但是,您可以使用列表:
String[] numberList = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
String[] suitList = {"Hearts", "Diamonds", "Clubs", "Spades"};
List<Card> deck = new ArrayList<>();
public static void main(String[] args) {
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 13; j++) {
deck.add(new Card(numberList[j], suitList[i]));
}
}
}