该代码打印每行的总和。
如何将其转换为每列显示总和?
谢谢,,

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

最佳答案

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

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

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

关于java - 从行到列添加,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13400936/

10-10 20:11