我正在制作一个生活游戏。
以下代码旨在检查一个点有多少个邻居。
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)
你们知道为什么当我处理所有可能的异常时仍然会发生越界异常吗?