Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查java 2d数组中的相邻元素_Java_Multidimensional Array - Fatal编程技术网

检查java 2d数组中的相邻元素

检查java 2d数组中的相邻元素,java,multidimensional-array,Java,Multidimensional Array,假设我有一个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&

假设我有一个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
            }
grid=new boolean[];

对于(int i=0;i在if语句的前端添加边界检查。例如:

if ((j + 1) < grid[i].length && grid[i][j + 1] == true)
if((j+1)
这将确保使用
j+1
不会越界。首先检查最左边的条件,如果它为false,则由于&&运算符,整个语句为false


因此,第二个条件
grid[i][j+1]==true
甚至不会被计算,您将避免IndexOutOfBoundsException.

好的。到目前为止您尝试了什么?一些if检查,如if(array2d[i,j+1]==true{do sth})、i,j-1,j,i+1,j。但是我越界了,请编辑您的问题以包含更多信息。