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

Java中填充长度为5的数组时,for循环为何抛出ArrayIndexOutOfBoundsException?

ArrayIndexOutOfBoundsException 原因分析与修复

错误原因

你写的循环条件i <= numeros.length是问题的核心:

  • 数组numeros的长度为5,numeros.length的返回值就是5
  • 循环会从i=0一直执行到i=5,当i=5时,你尝试访问numeros[5],但Java数组的索引范围是0到length-1(也就是0到4),这就触发了数组索引越界异常。

修复方案

把循环条件改成i < numeros.length,这样循环会在i=4时结束,刚好覆盖数组的所有有效索引:

public class Main {
    public static void main(String[] args) {

        int[] numeros = new int[5];

        for (int i = 0; i < numeros.length; i++) {
            numeros[i] = i;
        }
        System.out.println("Array filled successfully");
    }
}

你也可以写成i <= numeros.length - 1,效果和上面完全一致,都是限制i的最大值为4。

修改后运行程序,就能正常填充数组并打印成功提示信息了。

内容的提问来源于stack exchange,提问作者EMILYN VERENICE RECINOS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 07:34:52