[英]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.