您好,我正在为编程课编写程序,我得到:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 18
at Life.countNeighbors(Life.java:200)
at Life.genNextGrid(Life.java:160)
我以前遇到过ArrayIndexOutOfBoundsException
错误,通常是在我尝试添加或减去数组的索引时引起的。但是这次完全不同,我希望这里有人能指出错误发生的原因。
关于我的程序的信息:该程序就像 John Conway 的人生游戏。使用二维数组,然后将某些元素设置为(真 = 活着)或(假 = 死),程序然后根据它拥有的邻居数量确定细胞在下一代中是生还是死。(3个邻居=新细胞的诞生)(2,3个邻居=他们还活着)他们在下一代死去的任何其他东西。
根据我的编辑器,IndexOutOfBound 错误是由这一行引起的:
if(!(grid[1][1]) && !(grid[1][18]) && !(grid[18][1]) && !(grid[18][18]))
我将上面的行创建为约束,它不应该告诉 java 搜索超出原始数组范围的索引,因为它们最终只是布尔(真/假)语句。如果有人可以帮我调试这个错误,那就太好了。
这是我的代码:(不包括主要方法)
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
}