有PER PER行的麻烦

时间:2012-11-15 15:11:30

标签: java

我的代码遇到问题,我想按行打印ROW但是我最后添加了所有这些数字 -

应该是这样的 - >第0行的总和是“”                           第1行的总和是“”                           第2行的总和是“”

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 sum = 0;

               for ( int row=0; row < data.length; row++)
                 for ( int col=0; col < data[row].length; col++)
                   sum = sum + data[row][col];

                System.out.println( sum );
              }
}

3 个答案:

答案 0 :(得分:3)

您希望外部循环包含sum变量的初始化和打印:

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

答案 1 :(得分:0)

在第一个循环内移动总和以及打印。

 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.println( sum );
        }

答案 2 :(得分:0)

有两个变量并积累它。

int totalSum = 0;
for (int row = 0; row < data.length; row++) {
    int rowSum = 0;
    for (int col = 0; col < data[row].length; col++) {
        rowSum = rowSum + data[row][col];
    }
    System.out.println("Sum of " + (row + 1) + " is " + rowSum);
    totalSum += rowSum;
}
System.out.println("TotalSum " + totalSum);