如何遍历二维数组并按行主顺序计算每行中有多少元素大于1

How to traverse through 2d array and count how many elements are greater than 1 in each row in row major order

我正在编写一种方法,该方法以行优先顺序遍历二维数组,并在每行的开头将计数变量初始化为零。在内部循环中,如果值不为零,我会增加 count 变量。在行尾,如果 count 变量不正好等于 1,则 return false。我已经为此工作了大约 2 周,但找不到我的错误。请指出正确的方向。 ** 不要介意打印语句我想看看计数是多少,我的代码似乎只命中数组的第二行

public static boolean isGPM(int[][] matrix) {
    int count =0;
    for (int row = 0; row < matrix.length; row++) {
        count =0;
        for (int col = 0; col < matrix[row].length; col++) {
            if (matrix[row][col] > 0) {
                count++;
            }
            else {
                return !gpm;
            }
        }
    }
    System.out.println(count);
    return gpm;
}

如果我没理解错的话,你只关心每行的计数。这应该有效:

        int count = 0;

        // Process each row...
        for (int row = 0; row < matrix.length; row++) {

            count = 0;

            // Process each column...
            for (int col = 0; col < matrix[row].length; col++) {

                 // Check the cell.
                 if (matrix[row][col] != 0) {
                     count++;
                 }                     
            }
            // Row processing complete. Check count.
            if (count != 1) {
                System.out.println(count);
                return gpm;
            }
        }