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

如何用Java对二维数组的指定区域元素进行求和?

二维数组指定区域求和实现方案

首先明确你的需求:对数组中指定行的指定列范围元素求和(Java数组索引从0开始),对应目标元素:

  • 行索引1:列索引2到4(元素8、1、0)
  • 行索引2:所有列(元素6、9、6、3、4)
  • 行索引3:列索引0到2(元素5、4、2)

两种实现方式都可行

一次性遍历所有符合条件的元素求和,或者逐行计算后汇总,结果完全一致,只是代码组织逻辑不同。


方式1:一次性完成求和

直接针对每一行的列范围遍历累加,或通过配置行范围的方式统一处理:

class Lab {
    public static void main(String[] args) {
        int[][] scores = {
            {2, 8, 3, 2, 6},
            {3, 2, 8, 1, 0},
            {6, 9, 6, 3, 4},
            {5, 4, 2, 4, 5}
        };
        
        // 存储需要处理的行索引及对应的列起始、结束索引(闭区间)
        int[][] rowRanges = {{1, 2, 4}, {2, 0, 4}, {3, 0, 2}};
        int totalSum = 0;
        
        for (int[] range : rowRanges) {
            int row = range[0];
            int startCol = range[1];
            int endCol = range[2];
            
            for (int j = startCol; j <= endCol; j++) {
                totalSum += scores[row][j];
            }
        }
        
        System.out.println("总和:" + totalSum); // 输出48
    }
}

方式2:逐行求和后汇总

先实现单行指定列范围求和的方法,再分别调用后累加结果:

class Lab {
    public static void main(String[] args) {
        int[][] scores = {
            {2, 8, 3, 2, 6},
            {3, 2, 8, 1, 0},
            {6, 9, 6, 3, 4},
            {5, 4, 2, 4, 5}
        };
        
        int sumRow1 = sumRowRange(scores, 1, 2, 4);
        int sumRow2 = sumRowRange(scores, 2, 0, 4);
        int sumRow3 = sumRowRange(scores, 3, 0, 2);
        
        int totalSum = sumRow1 + sumRow2 + sumRow3;
        System.out.println("总和:" + totalSum);
    }
    
    // 计算指定行中,startCol到endCol(闭区间)的元素和
    private static int sumRowRange(int[][] matrix, int row, int startCol, int endCol) {
        int sum = 0;
        // 边界校验避免索引越界
        if (row < 0 || row >= matrix.length || startCol < 0 || endCol >= matrix[row].length || startCol > endCol) {
            return sum;
        }
        
        for (int j = startCol; j <= endCol; j++) {
            sum += matrix[row][j];
        }
        return sum;
    }
}

原代码的关键错误修正说明

你的示例代码存在几个核心问题:

  1. string 需改为Java规范的大写 String;
  2. sumRow 是实例方法,无法在static的main方法中直接调用,需改为static;
  3. scores[1][] 这类数组索引写法非法,变量 startrow 等未声明类型;
  4. for循环条件错误:i==lastrow 是相等判断,应改为范围遍历逻辑(如 i <= lastrow),且缺失循环变量递增逻辑;
  5. return sum 写在内部循环中,会导致第一次循环就直接返回,无法完成累加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:10:23