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
相关产品推荐
相关产品推荐

