我正在制作一场生活游戏。
以下代码用于检查某个点有多少个邻居。
public int neighbours(int x, int y){
int result = 0;
if(x!=0 && y!=0 && y!=getHeight() && x!= getLength()){
if (life[x - 1][y + 1] == 1)
result++;
else if (life[x][y + 1] == 1)
result++;
else if (life[x + 1][y + 1] == 1)
result++;
else if (life[x + 1][y] == 1)
result++;
else if (life[x + 1][y - 1] == 1)
result++;
else if (life[x][y - 1] == 1)
result++;
else if (life[x - 1][y - 1] == 1)
result++;
else if (life[x - 1][y] == 1)
result++;
} else if(x==0 && y==0){
if (life[x][y + 1] == 1)
result++;
else if (life[x + 1][y + 1] == 1)
result++;
else if (life[x + 1][y] == 1)
result++;
}
else if(x==0 && y==getHeight()){
if (life[x + 1][y] == 1)
result++;
else if (life[x + 1][y - 1] == 1)
result++;
else if (life[x][y - 1] == 1)
result++;
}
else if(y==getHeight() && x==getLength()){
if (life[x][y - 1] == 1)
result++;
else if (life[x - 1][y - 1] == 1)
result++;
else if (life[x - 1][y] == 1)
result++;
}
else if(y==0 && x==getLength()){
if (life[x - 1][y + 1] == 1)
result++;
else if (life[x][y + 1] == 1)
result++;
else if (life[x - 1][y] == 1)
result++;
}
else if (x==0){
if (life[x][y + 1] == 1)
result++;
else if (life[x + 1][y + 1] == 1)
result++;
else if (life[x + 1][y] == 1)
result++;
else if (life[x + 1][y - 1] == 1)
result++;
else if (life[x][y - 1] == 1)
result++;
}
else if(y==getHeight()){
if (life[x + 1][y] == 1)
result++;
else if (life[x + 1][y - 1] == 1)
result++;
else if (life[x][y - 1] == 1)
result++;
else if (life[x - 1][y - 1] == 1)
result++;
else if (life[x - 1][y] == 1)
result++;
}
else if(x==getLength()){
if (life[x - 1][y + 1] == 1)
result++;
else if (life[x][y + 1] == 1)
result++;
else if (life[x][y - 1] == 1)
result++;
else if (life[x - 1][y - 1] == 1)
result++;
else if (life[x - 1][y] == 1)
result++;
}
else if(y==0 && x!=getLength() && x!=0){
if (life[x - 1][y + 1] == 1)
result++;
else if (life[x][y + 1] == 1)
result++;
else if (life[x + 1][y + 1] == 1)
result++;
else if (life[x + 1][y] == 1)
result++;
else if (life[x - 1][y] == 1)
result++;
}
return result;
}
正如您所看到的,我试图解决所有异常,但程序一直给我以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 30
at LifeGrid.neighbours(LifeGrid.java:165)
at LifeGrid.run(LifeGrid.java:179)
at TestLife.main(TestLife.java:15)
当我处理所有可能的异常时,你们有没有想过为什么仍然会发生越界异常。
答案 0 :(得分:2)
你需要检查< getHeight / Width(),而不是==。如果它是== getHeight或getWidth,它将超出界限。
答案 1 :(得分:0)
您对y == getHeight()
的检查需要y == getHeight() - 1
,因为这是您在董事会最底层时所拥有的价值。此外,您对x == getLength()
的检查必须为x == getLength() - 1
,因为这是您在董事会右侧边缘时所拥有的价值。