[英]How do I sum a column if the rows and columns are not equal?
so I've gone on a few other summing columns in 2d arrays, but all of them have equal lengths whereas my does not.所以我在二维数组中进行了其他一些求和列,但它们的长度都相等,而我的则没有。 I have summed the rows (pretty straight forward), however, when I try to sum the column, it stops because there's not a number in the first row.我已经对行求和(非常直接),但是,当我尝试对列求和时,它停止了,因为第一行中没有数字。 How do I make it so it continues?我该如何让它继续下去? I have included what the output is.我已经包括了输出是什么。
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
*/
Thank you to everyone!谢谢大家!
Try this.尝试这个。 The trick is to fill in the empty columns with zeroes as placeholders:诀窍是用零作为占位符填充空列:
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
int length = 0;
for (int r = 0; r < data.length; r++) {
int currLength = data[r].length;
if(currLength>length) length = currLength;
}
// create array for column sums
int[] sums = new int[length];
// fill array with zeros
Arrays.fill(sums, 0);
// sum up
for (int currentRow = 0; currentRow < data.length; currentRow++) {
for (int col = 0; col < data[currentRow].length; col++) {
sums[col] += data[currentRow][col];
}
}
// print sums
for (int i = 0; i < sums.length; i++) {
System.out.println("Sum of column " + (i+1) + ": " + sums[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.