假设我有一个4X42D数组。例如
| 0 | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 |
| 8 | 9 | 10| 11|
| 12| 13| 14| 15| 我需要检查相邻的元素向上和左,而相邻的元素没有脱离束缚。例如0{1,4},3{2,7},5{1,4,6,9}。
有什么帮助吗?
谢谢
更多的炎症。
grid = new boolean [][];
for(int i=0;i<grid.length;i++){
for(j=0;j<grid.length; j++)
grid[i][j] = false;
}
grid[0][1]= true;
if(grid[i][j+1]]==true){
//do sth
}else if(grid[i][j-1]==true){
// do sth
}else if(grid[i-1][j]==true){
// do sth
}else if(grid[i+1][j]==true){
// do sth
}发布于 2014-07-05 16:08:38
将边界检查添加到if语句的前端。例如:
if ((j + 1) < grid[i].length && grid[i][j + 1] == true)这将确保您不会通过使用j + 1而越界。首先检查最左边的条件,如果为false,则整个语句由于&&运算符而为false。
因此,第二个条件grid[i][j + 1] == true甚至不会被计算,您将避免使用IndexOutOfBoundsException。
https://stackoverflow.com/questions/24587013
复制相似问题