[英]java index out of bounds exception using lists
我為列表中的項目符號和小怪列表創建了一些代碼。 我試圖做一些可以檢測到碰撞的東西,然后刪除子彈和暴民。 但是,我得到了
java.lang.IndexOutOfBoundsException
在這一行:
if(gmgr.bulletlist.get(i).x + x> = gmgr.moblist.get(mobnum).x && gmgr.bulletlist.get(i).x + x <= gmgr.moblist.get(mobnum).x + 32){
這是我的完整代碼:
for (int x = 0; x < gmgr.bulletlist.get(i).size; x++) {//size is the size of the bullet in pixels in this case 8
for (int y = 0; y < gmgr.bulletlist.get(i).size; y++) {
for (int mobnum = 0; mobnum < gmgr.moblist.size();//here size is the length of the list mobnum++) {
if(gmgr.bulletlist.get(i).x+x>=gmgr.moblist.get(mobnum).x&&gmgr.bulletlist.get(i).x+x<=gmgr.moblist.get(mobnum).x+32){//here I take the position of the bullet and add and check for collision on every pixel
if(gmgr.bulletlist.get(i).y+y>=gmgr.moblist.get(mobnum).y&&gmgr.bulletlist.get(i).y+y<=gmgr.moblist.get(mobnum).y+32){
gmgr.moblist.remove(mobnum);
mobnum-=1;//the problem is for as far as I know that I delete this while in this loop
gmgr.bulletlist.remove(i);
i-=1;
System.out.println("gotcha!!!!");//which means that the bullet hit the mob
}
}
}
}
}
我需要找到一種方法來刪除這些項目符號。 也歡迎任何改進我的代碼的想法
索引i
或mobnum
超出范圍。 最可能的原因是以下幾行:
gmgr.bulletlist.remove(i);
i-=1;
考慮i==0
。 您刪除位置0
處的項目,然后將i-=1
設置為i==-1
。 現在,在這三個循環中的任何一個的下一個迭代中,您都嘗試訪問gmgr.bulletlist.get(i)
,它將給出您發布的異常。
代碼有點混亂,但是:
gmgr.bulletlist.remove(i);
i-=1;
這里的一件事是,您不斷迭代其他生物。 因此,如果它是子彈0,那么下一個暴民將在索引-1處尋找子彈
為了更好地發現問題,您應該事先獲取對象,這樣可以避免刪除時出現索引問題,還可以使您清楚地了解正在發生的事情,因為當前異常可能引用了if中的任何列表。
另外,使用標記表示命中,然后跳到下一個項目符號
即
boolean hit = false;
Bullet bullet = gmgr.bulletlist.get(i);
for (int x = 0; x < bullet.size; x++) {
for (int y = 0; y < bullet .size; y++) {
for (int mobnum = 0; mobnum < gmgr.moblist.size(); mobnum++) {
Mob mob = gmgr.moblist.get(mobnum);
if(bullet.x+x>=mob.x && bullet.x+x<=mob.x+32){
if(bullet.y+y>=mob.y&&bullet.y+y<=mob.y+32){
gmgr.moblist.remove(mobnum);
gmgr.bulletlist.remove(i);
hit = true;
break; //skip other mobs, bullet is invalid
}
}
}
if(hit) break; //skip other bullet pixel, bullet is invalid
}
if (hit) { //move to the next bullet, reset hit flag
hit = false;
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.