public static boolean play123(ArrayList<Card>list){
boolean win=false;
int round=1;
for(int i = 0;i<=list.size();i++){
Deck.handOutNextCard(list);
if(list.get(i)==Card.AceClub ||list.get(i)== Card.AceDiamond ||list.get(i)== Card.AceHeart ||list.get(i)== Card.AceSpade){
if(round==1){
System.out.println("You loose! " +list.get(i)+"From round: "+round);
i = list.size()+1;
win = false;
}
}
else if(list.get(i)==Card.TwoClub ||list.get(i)== Card.TwoDiamond ||list.get(i)== Card.TwoHeart ||list.get(i)== Card.TwoSpade){
if(round==2){
System.out.println("You loose! " + list.get(i)+"From round: " +round);
i = list.size()+1;
win = false;
}
}else if(list.get(i)==Card.ThreeClub ||list.get(i)== Card.ThreeDiamond ||list.get(i)== Card.ThreeHeart ||list.get(i)== Card.ThreeSpade){
if(round==3){
System.out.println("You loose! " + list.get(i)+"From round: " +round);
i = list.size()+1;
win=false;
}
}else{
if(round<3){
list.remove(0);
i=0;
round++;
}else{
list.remove(0);
i=0;
round=1;
}
}
if(list.isEmpty()){
System.out.println("You win ! ");
win = true;
}
}
return win;
}
我有时会得到IndexOutOfBoundsException:Index:1,Size:0使用该方法时出错大约100次,可能是什么问题:// 我试图通过使用不同的循环类型来修复它,但这是不可能的,并且索引和大小有时是不同的,这是handOutNextCard(list)方法: public static Card handOutNextCard(ArrayListlist){
Card current = list.get(0);
list.remove(0);
return current;
}
答案 0 :(得分:2)
List
可以从0
到n - 1
进行寻址(其中n
是大小)。
for(int i = 0;i<=list.size();i++){
应该是
for(int i = 0; i < list.size(); i++){
List.get(int)
Javadoc说(对于Throws
)
IndexOutOfBoundsException
- 如果索引超出范围(index < 0 || index >= size())
此外,从Collection
移除项目的唯一安全方法(在您重复使用时)是Iterator.remove()
。其中的Javadoc(部分)
如果在迭代进行过程中以除了调用此方法之外的任何方式修改基础集合,则未指定迭代器的行为。