您好我正在编写一个编程类程序,我得到了一个:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 18
at Life.countNeighbors(Life.java:200)
at Life.genNextGrid(Life.java:160)
之前我遇到过ArrayIndexOutOfBoundsException
个错误,通常是在我尝试添加或减去数组索引时引起的。然而这次它完全不同了,我希望有人可以指出错误发生的原因。
关于我的节目的信息:该节目就像John Conway的生活游戏。使用2d数组,然后将某些元素设置为(true = alive)或(false = dead),然后程序根据它拥有的邻居数确定一个单元是否在下一代中生存或死亡。 (3个邻居=新细胞的诞生)(2,3邻居=他们还活着)他们在下一代死去的其他任何事情。
IndexOutOfBound错误是由我的编辑根据此行引起的:
if(!(grid[1][1]) && !(grid[1][18]) && !(grid[18][1]) && !(grid[18][18]))
我创建了上面的行作为约束,它不应该告诉java搜索超出原始数组边界的索引,因为它们最终只是booleans(true / false)语句。如果有人可以帮我调试这个错误的错误。
这是我的代码:(不包括主要方法)
public static void clearGrid ( boolean[][] grid )
{
int col;
int row = 1;
while(row < 18){
for(col = 1; col < 18; col++){
grid[row][col]= false;//set each row to false
}
row++;
}//set all elements in array to false
}
public static void genNextGrid ( boolean[][] grid )
{
//new tempprary grid
boolean[][] TempGrid = new boolean[GRIDSIZE][GRIDSIZE];
TempGrid= grid; // copy the current grid to a temporary grid
int row = 1;
int col = 1;
countNeighbors(TempGrid, row, col); // passes the TempGrid to countNieghbor method
for(row = 1; row < 18; row++){
countNeighbors(TempGrid, row, col);
for(col = 1; col < 18; col++){
countNeighbors(TempGrid, row, col);
if(countNeighbors(grid, row, col) == 3)
{
TempGrid[row][col] = true;
}
else if(countNeighbors(grid, row, col) == 2 || countNeighbors(grid, row, col) == 3)
{
TempGrid[row][col] = true;
}
else
{
TempGrid[row][col] = false;
}
}
}
}
public static int countNeighbors ( final boolean[][] grid, final int row, final int col )
{
int n = 0; //int used to store the # of neighbors
int temprow = row;
int tempcol = col;
//count # of neighbors for the cell on the edge but not the corner
for(temprow = row; temprow <= 18; temprow++)
{
for(tempcol = row; tempcol <= 18; tempcol++)
{
if(temprow == 1 || temprow == 18 || tempcol == 1 || tempcol ==18)
{
if(!(grid[1][1]) && !(grid[1][18]) && !(grid[18][1]) && !(grid[18][18]))
{
if(grid[temprow][tempcol] == true)
{
n++;
}
}
}
}
}
//count # of neighbors for the corner cells
for(temprow = row; temprow <= 18; temprow++)
{
for(tempcol = row; tempcol <= 18; tempcol++)
{
if(grid[1][1] || grid[1][18] || grid[18][1] || grid[18][18])
{
if(grid[temprow][tempcol] == true)
{
n++;
}
}
}
}
// count the cells that are not on the edge or corner
while(temprow >= 2 && tempcol >= 2 && temprow <= 17 && tempcol <= 17)
{
for(temprow = row; temprow-1 <= temprow+1; temprow++)
{
for(tempcol = col; tempcol-1 <= tempcol+1; tempcol++)
{
if(grid[temprow][tempcol] == true)
{
n++;
}
}
}
}
return n; // return the number of neighbors
}
答案 0 :(得分:7)
如果没有完整的堆栈跟踪以及问题所在的指示,这是我最好的猜测:
grid[18][1]
值18
超出了您可以访问的数组的大小,在Java数组中基于零(0)
。由于我在整个帖子中都看到了17
,这似乎是最合乎逻辑的原因。
答案 1 :(得分:5)
在Java中,数组索引的编号从0
到n-1
。通过查看您的代码,它似乎假设它们的编号从1
到n
。