如何在多维数组中计算包含零的COLUMNS的数量

时间:2016-04-15 05:54:37

标签: java arrays multidimensional-array

如何在多维数组中计算包含零的COLUMNS的数量。 我能够计算包含零的行数,但我无法理解如何计算列数。请帮忙。

public class Main {
    public static void main (String[] args) {
        int i;
        int j;
        int count = 0;
        int [][] arr = {{3, 0, 0, 6}, {4, 0, 1, 1}};
        for (i = 0; i < arr.length; i++) {
            System.out.println();
            for (j = 0; j < arr[i].length; j++){
                System.out.print(arr[i][j] + ", ");
            }
        }
        System.out.println();
        //-----------------------------------------------------------
        for (i = 0; i<arr.length; i++) {
            for (j = 0; j<arr[i].length; j++) {
                if (arr[i][j] == 0) {
                    count++;
                    break;
                 }
            }
        }
        System.out.println("the amount of rows containing zeros = " + count);
    }
}

1 个答案:

答案 0 :(得分:1)

另一种直接获得sqaure矩阵相同结果的方法:

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int i;
        int j;
        int count = 0;
        int [][] arr = {{3, 0, 0, 6}, {4, 0, 1, 0}};

        for (i = 0; i < arr.length; i++)
        {
            System.out.println();
            for (j = 0; j < arr[i].length; j++)
            {
                System.out.print(arr[i][j] + ", ");} }
                System.out.println();
            //--------------------------------------------------------------------

            for (i = 0; i<arr.length; i++)
                for (j = 0; j<arr[i].length; j++)
                    if (arr[i][j] == 0)
                    {
                        count++;
                        break;
                    }
            System.out.println("the amount of rows containing zeros = " + count);

            //--------------------------------------------------------------------
            count=0;

            for (i = 0; i<arr[0].length; i++)
                for (j = 0; j<arr.length; j++)
                    if (arr[j][i] == 0)
                    {
                        count++;
                        break;
                    }
            System.out.println("the amount of cols containing zeros = " + count);
    }
}

输出:

3, 0, 0, 6, 
4, 0, 1, 0, 
the amount of rows containing zeros = 2
the amount of cols containing zeros = 3

http://ideone.com/VE0qAw