开发者

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 p开发者_如何学运维rint 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++)


Indexes start from 0 so last index is 63. Change your for loop like this:
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 i.e. 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.


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


You've done your math wrong. Arrays begin counting at 0. E.g. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜