Arraylist突然被认为是空的
问题描述:
我负责编写一个21点游戏,我创建了一个卡片类,它有一个int值和一个带卡片颜色的字符串(心,俱乐部,钻石和铲子)。我组织了一个包含所有52张牌的ArrayList的“牌组”牌。当我想给一个卡我用下面的代码:Arraylist突然被认为是空的
public Card give(){
Card d = c.get(0); //c is the Arraylist
c.remove(0);
return d;
}
,因为我已经使用6层甲板我创建了一个名为playdeck另一个类,其中有6个“甲板”对象的数组。在这里,我简单地使用这个代码,即可获得一张牌:作为程序试图进入第三甲板对象并获取卡
class playdeck{enter code here
static int x = 0;
static int y = 0;
static deck[] play = new deck[6];
public playdeck(){
play[0] = new deck();
play[1] = new deck();
play[2] = new deck();
play[3] = new deck();
play[4] = new deck();
play[5] = new deck();
}
public static Card give(){
y++;
if(y == 53){
y = 0;
x++;
}
Card d = play[x].give();
return d;}
一切工作正常进行第2层甲板,但不久,出现以下错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out-of-bounds for length 0 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:439)
at deck.give(deck.java:39)
at playdeck.give(playdeck.java:23)
at Blackjack.main(Blackjack.java:5)
当我尝试访问的第三个“甲板”的对象,一切工作正常,以及所有其他的“甲板”的对象,但只要我尝试发出的卡超过2包,该程序崩溃。有没有人为什么会发生这种情况?这里的“我的主要方法BTW:
public static void main (String[] args){
playdeck blackjack = new playdeck();
for (int x = 0; x < 312; x++){
System.out.println(blackjack.give().name);
}}
答
-
你确定它需要从
ArrayList
每次取出存储卡,当你需要它,因为你可以做如下:?static int i = 0; public Card give() { return c.get(i++); }
即使需要从
ArrayList
中删除对象,然后替换public Card give(){ Card d = c.get(0); //c is the Arraylist c.remove(0); return d; }
与
public Card give(){ return c.remove(0); }
-
错误是在这里:
public static Card give(){ y++; if(y == 53){ y = 0; x++; } Card d = play[x].give(); return d; }
因为你正确处理只卡第一层甲板,而忘记了别人。你为什么要在构造函数中分配'play`的元素
static int i = 0; public static Card give() { i++; y = i % 52; //0-51 x = i/52; //0-5 return play[x].give(); }
并请,看一看的Java coding conventions
:此代码将解决问题了吗?这意味着每次创建'playdeck'实例时,您都要覆盖'play'的元素。 'play'不应该是静态的,或者你应该使用静态初始化器而不是构造器。 –