如何检查2D布尔数组网格中每个单元格的周围?

时间:2015-10-20 23:44:35

标签: java grid cell

我有一个打印O或 - 的for循环,具体取决于2D布尔数组中的值是否称为' grid'是真是假,如下:

    boolean[][] grid = new boolean[10][10];
    grid[1][1] = true;
    grid[2][2] = true;

    for (int i = 0; i < grid.length; i++){
        for (int j = 0; j < grid.length; j++){
            if (grid[i][j] == true){
                System.out.print("O");
            }
            else{
                System.out.print("-");
            }
        }
        System.out.println();
    }

我想知道如何在程序的后期成功检查(然后打印)有多少O(如果有的话)围绕网格的每个单元格。

这是我的尝试:

    int countO = 0;

    for (int i = 0; i < grid.length; i++){
        for (int j = 0; j < grid.length; j++){
            if (grid[i - 1][j - 1] == true){
                countO++;
            }
            if (grid[i - 1][j + 1] == true){
                countO++;
            }
            if (grid[i + 1][j + 1] == true){
                countO++;
            }
            if (grid[i + 1][j - 1] == true){
                countO++;
            }
        }
    }

    System.out.println(countO);

但我甚至无法成功测试它而不会出错。

0 个答案:

没有答案