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

Java数组逐元素累加累减累乘运算异常与下标越界问题求助

代码问题核心原因

  • 第一版循环中错误使用数组索引i参与运算,而非数组实际存储的元素值array[i]
  • 差值计算的初始值设置错误:直接用difference -= 元素相当于默认初始值为0,正确逻辑应该以第一个元素为初始值,再依次减去后续元素
  • 第二版循环的终止条件错误:访问i+1时,循环最大索引只能到数组长度-2,否则会触发数组越界异常

正确实现逻辑

  1. 先做边界判断:数组为空时可自定义返回规则;数组长度为1时,和、差、积都等于该元素本身,避免出现单元素差值为负的问题
  2. 三个运算变量的初始值都取数组第一个元素
  3. 从数组第二个元素开始遍历,依次执行运算
  4. 遍历完成后按要求格式化输出

示例代码

public class ArrayCalculate {
    public static void main(String[] args) {
        int[] array = {25, -6, 14, 7, 100};
        // 数组为空校验
        if (array.length == 0) {
            System.out.println("数组为空");
            return;
        }
        // 初始化运算变量为第一个元素值
        int sum = array[0];
        int difference = array[0];
        int product = array[0];
        // 从第二个元素开始遍历运算
        for (int i = 1; i < array.length; i++) {
            sum += array[i];
            difference -= array[i];
            product *= array[i];
        }
        // 格式化输出结果
        System.out.printf("Sum:        = %d%n", sum);
        System.out.printf("Difference: = %d%n", difference);
        System.out.printf("Product:    = %d%n", product);
    }
}

运行结果

Sum:        = 140
Difference: = -90
Product:    = -147000

单元素数组{32}测试输出:

Sum:        = 32
Difference: = 32
Product:    = 32

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:24:07