0

我的代码有问题,我想逐行打印它,但我最终添加了所有这些数字-

应该看起来像这样 --> 第 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 );
              }
}
4

3 回答 3

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);
}
于 2012-11-15T15:12:37.073 回答
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 );
        }
于 2012-11-15T15:12:44.970 回答
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);
于 2012-11-15T15:16:48.273 回答