你好我寫一個程序編程類,我得到一個:奇怪IndexOutOfBound錯誤
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搜索索引超出了原來的數組的邊界因爲他們最終只是布爾(真/假)陳述。如果任何人都可以幫助我調試這個出色的錯誤。
這裏是我的代碼:(不包括主要方法)
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
}
我們不知道這些行如何與您提供的代碼相對應。請註明實際出錯的地方是 – Woot4Moo