0

此代码打印每行的总和....如何转换它以便打印每列的总和?谢谢,,

public class NewClass{
  public static void main( String[] arg )
  {
int[][] data = 
    { { 1, 2},
      { 2, 2},
      { 1, 2, 4, 5},
      { 2, 2, 4,},
      { 1, 1, 4, 5 },
      { 2, 1, }};



     for ( int row=0; row < data.length; row++)
        {
           int sum = 0;
          for ( int col=0; col < data[row].length; col++)
          {
           sum = sum + data[row][col];
          }
            System.out.print("Sum of Row " + row+" is :  ");
          System.out.println( sum );
        }         
      }
    }     
4

1 回答 1

1

您必须考虑到每行中的列数是不同的。

首先,您找到数据集中的最大列数,然后对列求和。

public class NewClass {
    public static void main(String[] arg) {
        int[][] data = { { 1, 2 }, { 2, 2 }, { 1, 2, 4, 5 }, { 2, 2, 4, },
                { 1, 1, 4, 5 }, { 2, 1, } };

        int maxColLength = 0;
        for (int row = 0; row < data.length; row++) {
            int colLength = data[row].length;
            if (colLength > maxColLength) {
                maxColLength = colLength;
            }
        }

        for (int col = 0; col < maxColLength; col++) {
            int sum = 0;
            for (int row = 0; row < data.length; row++) {
                if (col < data[row].length) {
                    sum = sum + data[row][col];
                }
            }
            System.out.print("Sum of Column " + col + " is :  ");
            System.out.println(sum);
        }
    }
}
于 2012-11-15T16:41:46.850 回答