ArrayIndexOutOfBoundsException when repeating all elements of an array

how to handle this exception "ArrayIndexOutOfBoundsException" my code: I create an array of length 64, then I index each index, then print the indexes to make sure that I fill all the indexes, but prints to 63, and then gives an 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);
    }

}
+3
source share
7 answers

Array indices in Java begin with 0and go to array.length - 1. So change the loop tofor(int i=0;i<a.length;i++)

+15
source

Indexes start at 0, so the last index is 63. Modify the for loop as follows:
for(int i=0;i<a.length;i++){

+3
source

JLS-:

n , , n - ; 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]);

}
+3

?

0. , 64 , 0 to 63. 64- , a[63].

, , for(int i=1;i<=a.length;i++) a.length , 64.

:

  • 1 i.e. i=1, , , 0th.
  • a[64], 65th . 64 . , ArrayIndexOutOfBoundsException.

for:

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

, 0 < array.length.

+1

Java 0. , , 64, 64 + 1 = 65.

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

:

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

. 0. . int [] d = new int [2] - 0 1.

"i" 0, 1, . 1, for ArrayIndexOutOfBoundsException.

0

Source: https://habr.com/ru/post/1779818/


All Articles