我正在寻找一种方法来添加具有不同长度数组的二维数组的列中的所有元素。我快到了,但我不明白为什么程序突然做一些看似违背代码指示的事情。显然它只是按照代码的指示去做,但我无法确切地辨别出什么以及为什么。感谢帮助。
公共类主要{ 公共静态无效主(字符串[] args){
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
int total = 0;
int tick = 4;
int row = 0;
for (int col = 0; col != 5; col++) {
for (int num = 0; num < data.length; num++) {
if (col != 0 && data[row].length<col+1){
row++; //checks to see whether or not the column num is in range of the subarray
}
total += data[row][col];
if (row == tick-1) {
System.out.println(total);
}
row++;
if (row == tick) { //stops row from going over max
row = 0;
total = 0;
}
}
}
}
}
该错误在于您跳过列数少于当前列数的行的逻辑。
在第 5 次迭代中,当
col = 4
时,行跳过像这样工作
Iteration for the inner for loop when col 3
num goes from 0 .. 3
Iteration 1 (num = 0)
[row = 0]
Row 0 : Size [3] Skip by doing row++
[row = 1]
Do logic of adding number from Row 1 into total, row++
[row = 2]
Iteration 2 (num = 1)
[row = 2]
Row 2 : Size [4] Skip by doing row++
[row = 3]
Do logic of adding number from Row 3 into total, row++
[row = 4]
Logic to reset row and total get triggered resetting both to 0
正如您所看到的,您在第二次迭代本身中勾选了休息,然后内部循环再运行 2 次,将错误的值添加回总计中。
更好的方法是维护一个保存按列求和的输出数组
public class Main {
public static void main(String[] args)
throws Exception {
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
ArrayList<Integer> columnWiseSum = new ArrayList<>();
for (int rowIndex = 0; rowIndex < data.length; rowIndex++) {
int[] row = data[rowIndex];
for (int colIndex = 0; colIndex < row.length; colIndex++) {
// Insert a column into the output list if it does not exist
if (columnWiseSum.size() - 1 < colIndex) {
columnWiseSum.add(0);
}
int cellValue = data[rowIndex][colIndex];
// Add the value of this cell into the output
columnWiseSum.set(colIndex, columnWiseSum.get(colIndex) + cellValue);
}
}
System.out.println(columnWiseSum);
}
}