我已经创建了52张要添加到我的ArrayList的卡,唯一的问题是当我尝试获取列表中的第一项时,我可以进行outofboundserror,因为我不认为有任何内容已添加到我的ArrayList中。 / p>
private ArrayList<Card> deck;
public Deck() {
deck = new ArrayList<Card>();
for(int i = 1; i < 14; i++) {
if(i == 1){
Card c = new Card("Ace", "Hearts");
}
else if(i < 11 && i > 1) {
Card c = new Card("" + i, "Hearts");
}
else if(i == 11) {
Card c = new Card("Jack", "Hearts");
}
else if(i == 11) {
Card c = new Card("Queen", "Hearts");
}
else if(i == 11) {
Card c = new Card("King", "Hearts");
}
}
for(int i = 1; i < 14; i++) {
if(i == 1) {
Card c = new Card("Ace", "Clubs");
}
else if(i < 11 && i > 1) {
Card c = new Card("" + i, "Hearts");
}
else if(i == 11) {
Card c = new Card("Jack", "Clubs");
}
else if(i == 11) {
Card c = new Card("Queen", "Clubs");
}
else if(i == 11) {
Card c = new Card("King", "Clubs");
}
}
for(int i = 14; i < 1; i--) {
if(i == 11) {
Card c = new Card("King", "Diamonds");
}
else if(i == 11) {
Card c = new Card("Queen", "Diamonds");
}
else if(i == 11) {
Card c = new Card("Jack", "Diamonds");
}
else if(i < 11 && i > 1) {
Card c = new Card("" + i, "Diamonds");
}
else if(i == 1) {
Card c = new Card("Ace", "Diamonds");
}
}
for(int i = 14; i < 1; i--) {
if(i == 11) {
Card c = new Card("King", "Spades");
}
else if(i == 11) {
Card c = new Card("Queen", "Spades");
}
else if(i == 11) {
Card c = new Card("Jack", "Spades");
}
else if(i < 11 && i > 1) {
Card c = new Card("" + i, "Spades");
}
else if(i == 1) {
Card c = new Card("Ace", "Spades");
}
}
}
我如何将其添加到我的ArrayList?
答案 0 :(得分:2)
要将牌添加到牌组,您需要拨打
deck.add(c);
顺便说一下,使用循环并检查循环中的一个值是没有意义的。你可以只调用一行代码。
List<Card> deck = new ArrayList<>();
for (String suit : "Hearts,Clubs,Diamonds,Spades".split(",")) {
deck.add(new Card("Ace", suit));
for (int i = 2; i <= 10; i++)
deck.add(new Card("" + i, suit));
deck.add(new Card("Jack", suit));
deck.add(new Card("Queen", suit));
deck.add(new Card("King", suit));
}