繁体   English   中英

迭代遍历数组的所有元素时出现ArrayIndexOutOfBoundsException

[英]ArrayIndexOutOfBoundsException when iterating through all the elements of an array

如何处理这个异常“ArrayIndexOutOfBoundsException”我的代码:我创建一个64长度的数组然后我初始化每个索引然后我打印索引,以确保我正在填充所有索引,但它打印到63然后给出异常! 任何想法

    public static void main(String [] arg) {
    int [] a=new int [64];
    for(int i=1;i<=a.length;i++){
        a[i]=i;
        System.out.println(i);
    }

}

Java中的数组索引从0开始,然后转到array.length - 1 所以将循环更改为for(int i=0;i<a.length;i++)

索引从0开始,因此最后一个索引是63.更改for循环,如下所示:
for(int i=0;i<a.length;i++){

请参阅JLS-Arrays

如果一个数组有n个组件,我们说n是数组的长度; 使用从0到n-1(包括0和n-1)的整数索引来引用数组的组件。

所以你必须遍历[0,length()-1]

for(int i=0;i<a.length;i++) {
    a[i]=i+1;  //add +1, because you want the content to be 1..64
    System.out.println(a[i]);

}

需要完整的解释? 读这个

数组的索引始终从0开始。 因此,当您在数组中有64个元素时,它们的索引将从0 to 63 如果你想访问第64个元素,那么你必须通过a[63]来完成它。

现在,如果我们查看你的代码,那么你已经写了条件for(int i=1;i<=a.length;i++)这里a.length将返回数组的实际长度64。

这里发生了两件事

  1. 当您从1开始索引时,即i=1因此您将跳过数组的第一个元素,它将位于第0th索引处。
  2. 在最后,它试图访问a[64]元素,它将成为数组的65th元素。 但是你的数组只包含64个元素。 因此,您将获得ArrayIndexOutOfBoundsException

使用for循环迭代数组的正确方法是:

for(int i=0;i < a.length;i++)

索引从0开始并转到< array.length

你的数学错了。 数组从0开始计数。例如int [] d = new int [2]是一个计数为0和1的数组。

必须将整数“i”设置为0而不是1才能使其正常工作。 因为从1开始,你的for循环计数超过数组的限制,并给你一个ArrayIndexOutOfBoundsException。

在Java数组中,始终从索引0开始。因此,如果您希望数组的最后一个索引为64,则该数组的大小必须为64 + 1 = 65。

//                       start   length
int[] myArray = new int [1    +  64    ];

你可以这样纠正你的程序:

int i = 0;     // Notice it starts from 0
while (i < a.length) {
    a[i]=i;
    System.out.println(i++);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM