【发布时间】:2020-03-08 20:57:12
【问题描述】:
所以我已经在 2d 数组中进行了其他一些求和列,但它们都具有相同的长度,而我的没有。我已经对行求和(非常简单),但是,当我尝试对列求和时,它会停止,因为第一行中没有数字。我怎样才能让它继续?我已经包括了输出是什么。
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[])
{
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
// declare the sum
int sum;
int sum2 = 0;
// compute the sums for each row
for ( int row=0; row < data.length; row++)
{
// initialize the sum, i did it to zero
sum = 0;
// compute the sum for this row
for ( int col=0; col < data[row].length; col++)
{
sum+=data[row][col];
}
// write the sum for this row
System.out.println("The sum of this row is: " + sum);
}
for(int i = 0; i < data[0].length; i++)
{
sum2= 0;
for(int j = 0; j < data.length; j++)
{
sum2 = sum2 + data[j][i];
}
System.out.println("Sum of " + (i+1) +" column: " + sum2);
}
}
}
/*Sample Output:
The sum of this row is: 10
The sum of this row is: 30
The sum of this row is: 12
The sum of this row is: 2
Sum of 1 column: 13
Sum of 2 column: 9
Sum of 3 column: 15
*/
谢谢大家!
【问题讨论】:
标签: arrays loops multidimensional-array