所以我有一个我正在使用的2D角色阵列。每个空间可以被“C”,“M”或“N”(意思不重要)占据。我有两个方法,一个检查元素周围的4个空格,另一个检查元素周围的8个空格。这是前者。
public boolean checkAnySpace4(char[][] grid, int x, int y)
{
if(grid[x-1][y] == 'N' || grid[x-1][y] == 'M'|| grid[x-1][y] == 'C')
{
return false;
}
if(grid[x-1][y-1] == 'N' || grid[x-1][y-1] == 'M'|| grid[x][y-1] == 'C')
{
return false;
}
if(grid[x][y-1] == 'N' || grid[x][y-1] == 'M'|| grid[x][y-1] == 'C')
{
return false;
}
if(grid[x+1][y] == 'N' || grid[x+1][y] == 'M'|| grid[x+1][y] == 'C')
{
return false;
}
else
return true;
}
我只是希望方法在任何周围元素(无论是4还是8)已被占用时返回false,如果所有元素都已打开,则返回true。我该怎么做才能得到IndexOutOfBounds错误?
编辑:这是代码的其余部分。
public void start(int steps)
{
char [][] grid = new char[25][25];
int numCells = 0;
while (numCells < 10) {
//System.out.println("step = " + i);
int random = (int) Math.floor((Math.random() * 24));
int random2 = (int) Math.floor((Math.random() * 24));
if(checkGrid(grid, random, random2) == true) //if current cell is empty
{
addCellToGrid(grid, random, random2, 'N');//add cell with different coordinates
numCells++;
}
}
printGrid(grid);
System.out.print("exiting before steps");
//System.exit(-1);
/*
* Fix array index out of bounds error
*
*/
for(int i = 0; i < steps; i++)//populate array
{
for(int j = 0; j < 25; j++)
{
for(int k = 0; k < 25; k++)
{
if(new Random().nextDouble() <= (1-e)) //probability that cell dies
{
die(grid, j, k);
continue;
}
else ////if not dead, mutate with prob p_n for N,M cells, p_c for C cells
{
if(new Random().nextDouble() <= m) //mutate with prob m
{
mutate(grid, j,k);//mutate cell
if(grid[j][k] == 'N' || grid[j][k] == 'M')//if cell is type N or M
{
if(checkAnySpace4(grid, j, k))//if cell has space to divide
{
if(new Random().nextDouble() <= p_n)//divide with probability p_n
{
divide(grid, j, k);//divide cell
}
}
else
{
continue; //cell does not divide, do nothing
}
}
}
if(grid[j][k] == 'C')//C grid[j][k]s cannot mutate
{
if(checkAnySpace8(grid, j, k))//if cell has space to divide
{
if(new Random().nextDouble() <= p_c)//divide with probability p_c
{
divide(grid, j, k);//divide cell
}
}
}
}
}
}
}
printGrid(grid);
}
在checkAnySpace4方法的第一个if语句中抛出错误。
答案 0 :(得分:0)
在函数中再添加两个变量:size_x
和size_y
到函数。
然后:
public boolean checkAnySpace4(char[][] grid, int x, int y, int size_x, int size_y)
{
if(x == 0 || y == 0 || x == size_x || y == size_y){
/*complain on the console or raise an exception*/
return false;
}
if(grid[x-1][y] == 'N' || grid[x-1][y] == 'M'|| grid[x-1][y] == 'C')
{
return false;
}
if(grid[x-1][y-1] == 'N' || grid[x-1][y-1] == 'M'|| grid[x][y-1] == 'C')
{
return false;
}
if(grid[x][y-1] == 'N' || grid[x][y-1] == 'M'|| grid[x][y-1] == 'C')
{
return false;
}
if(grid[x+1][y] == 'N' || grid[x+1][y] == 'M'|| grid[x+1][y] == 'C')
{
return false;
}
else
return true;
}
您可能需要从size_x和size_y中减去1。