You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对变长二维数组的列元素求和?代码异常排查求助

二维数组变长子数组的列求和问题

核心思路

对包含不同长度子数组的二维数组求某一列的和,关键是遍历每一行时,判断当前行的长度是否大于目标列的索引(数组索引从0开始),若满足则将该行对应列的元素加入总和,否则跳过该行的该列元素。

原代码的问题

  • 嵌套循环逻辑混乱:外层遍历列、内层遍历行时,row变量被随意递增和重置,导致数组索引访问错误,甚至可能触发ArrayIndexOutOfBoundsException。
  • 列存在性判断错误:col != 0 && data[row].length<col+1的条件完全不符合需求,应该针对当前遍历的行判断是否包含目标列,而非用混乱的row变量做判断。
  • 累加逻辑被打断:循环中频繁重置total和row,导致正常的累加过程被破坏,无法得到正确的列总和。

修正后的代码

单指定列求和

如果只需要计算某一列(比如第5列,对应索引4)的和:

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} };
        
        int targetCol = 4; // 目标列索引,对应第5列
        int total = 0;
        
        for (int[] row : data) {
            // 检查当前行是否包含目标列
            if (targetCol < row.length) {
                total += row[targetCol];
            }
        }
        
        System.out.println("第" + (targetCol + 1) + "列的和为:" + total);
    }
}

所有列求和

如果需要计算所有存在列的和:

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} };
        
        // 先确定数组的最大列数
        int maxCols = 0;
        for (int[] row : data) {
            maxCols = Math.max(maxCols, row.length);
        }
        
        // 遍历每一列计算总和
        for (int col = 0; col < maxCols; col++) {
            int total = 0;
            for (int[] row : data) {
                if (col < row.length) {
                    total += row[col];
                }
            }
            System.out.println("第" + (col + 1) + "列的和为:" + total);
        }
    }
}

内容的提问来源于stack exchange,提问作者andrewc2023

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:17:46