简体   繁体   中英

ArrayIndexOutOfBoundsException when iterating through all the elements of an array

how to handle this exception "ArrayIndexOutOfBoundsException" my code : I create an array of 64 length then I intialized every index then I print the indexes to make sure I am fulling all indexes but it prints up to 63 then gives the exception !! any idea

    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);
    }

}

The array indexes in Java start from 0 and go to array.length - 1 . So change the loop to for(int i=0;i<a.length;i++)

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

See the JLS-Arrays :

If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

So you have to iterate through [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]);

}

Need Complete Explanation? Read this

The index of an Array always starts from 0 . Therefore as you are having 64 elements in your array then their indexes will be from 0 to 63 . If you want to access the 64th element then you will have to do it by a[63] .

Now if we look at your code, then you have written your condition to be for(int i=1;i<=a.length;i++) here a.length will return you the actual length of the array which is 64.

Two things are happening here:

  1. As you start the index from 1 ie i=1 therefore you are skipping the very first element of your array which will be at the 0th index.
  2. In the last it is trying to access the a[64] element which will come out to be the 65th element of the array. But your array contains only 64 elements. Thus you get ArrayIndexOutOfBoundsException .

The correct way to iterate an array with for loop would be:

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

The index starting from 0 and going to < array.length .

You've done your math wrong. Arrays begin counting at 0. Eg int[] d = new int[2] is an array with counts 0 and 1.

You must set your integer 'i' to a value of 0 rather than 1 for this to work correctly. Because you start at 1, your for loop counts past the limits of the array, and gives you an ArrayIndexOutOfBoundsException.

In Java arrays always start at index 0. So if you want the last index of an array to be 64, the array has to be of size 64+1 = 65.

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

You can correct your program this way :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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