从行到COLUMN添加

时间:2012-11-15 15:39:20

标签: java

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

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 );
        }         
      }
    }     

1 个答案:

答案 0 :(得分: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);
        }
    }
}