So I have a 2D character array that I am working with. Each space may either be occupied by a 'C', 'M', or 'N'(meaning not important). I have two methods, one that checks 4 spaces around an element, and one that checks 8 spaces around an element. Here is the former.
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;
}
I simply want the method to return false if any of the surrounding elements(whether 4 or 8) are already occupied, or true if all are open. How would I do this so that I don't get an IndexOutOfBounds error?
Edit: Here is the rest of the code.
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);
}
The error is thrown at the first if statement of the checkAnySpace4 method.