[英]Calculating sum of columns in uneven 2D array
我一直在通过一些免费的在线教程自学Java,并挑战自己完成几乎所有练习。 我已经坚持了一个星期,这让我发疯。 我觉得我已经很接近了,只是被组成不均匀列的各种数组长度绊倒了。
public class Testing {
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} };
int sum = 0;
int row = 0;
int col = 0;
int currentRow = 0;
while (currentRow < data.length) {
for (col = 0; col < data[currentRow].length; col++) {
sum = 0;
for (row = 0; row < data.length; row++) {
System.out.println(data[row][col]);
sum += data[row][col];
}
System.out.println("Sum: " + sum);
}
currentRow++;
}
}
}
好像有一个循环太多了。 您的while
遍历了第一个维度,而for(row...
是第二个维度。因此,无需通过for(row...
再次遍历数据for(row...
public class Testing {
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} };
int sum = 0;
for (int currentRow = 0; currentRow < data.length; currentRow++) {
sum = 0;
for (int col = 0; col < data[currentRow].length; col++) {
System.out.println(data[currentRow][col]);
sum += data[currentRow][col];
}
System.out.println("Sum: " + sum);
}
}
}
public class Testing {
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} };
// get max length of a row == number of columns
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++) {
System.out.println(data[currentRow][col]);
sums[col] += data[currentRow][col];
}
}
// print sums
for (int i = 0; i < sums.length; i++) {
System.out.println(i + ": " + sums[i]);
}
}
}
如果我正确理解您的问题,并且想要第一,第二,第三等列的总和,则可以尝试以下操作。
// array for the sums of the columns
int[] colSums;
int largestSize = 0;
// loop through and find the largest array of values (in this example its the 4th)
for(int x = 0; x < data.length; x++) {
largestSize = Math.max(largestSize,data[x].length);
}
colSums = new int[largestSize]; // create the int array with the right length
// loop through the data array and add sums to the colSums array
for(int x = 0; x < data.length; x++) {
colSums[x] = 0; // so that its not null when we add to it
for(int y = 0; y < data[x].length; y++) {
// here I add the number to the solSums array
colSums[y] += data[x][y];
}
}
// now colSums[0] will be the sum of the first column, colSums[1] = sum of second, etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.