When executing this code:

int x = 0, y = 0; int Arr1[] = new int[x]; //x - simple for (i = 2; i < 100; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { flag = false; y++; break; } } if (flag) { System.out.println(i); x++; Arr1[x - 1] = i; //Π’ этой строкС ошибка } flag=true; } 

an error occurs:

java.lang.ArrayIndexOutOfBoundsException: 0

Why does it occur?

  • First, specify the line on which the error occurred. Secondly, read what this error means and specify the length of the array and the index by which you refer to it. Unrelated code, delete the error mercilessly. - default locale
  • You can read the definition here: ru.stackoverflow.com/questions/501586/… - default locale
  • Error code Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 Error string (29) at example.hello.main (hello.java:29) - Konstantin Kotov
  • Here you can not see which line is the 29th. Mark it in question (it can be edited with the "edit" button in question). Remove the extra code. - default locale
  • if (flag) {System.out.println (i); x ++; Arr1 [x - 1] = i; // 29 line} flag = true; - Konstantin Kotov

1 answer 1

From the ArrayIndexOutOfBoundsException documentation:

Thrown to indicate that an array has been accessed with an illegal index. The size of the array.

Thrown to indicate that the array was accessed at an incorrect index. The index is either negative or not less than the size of the array.

Those. an array of length l can be accessed by indices from 0 to l-1 .

The error occurs either when addressing the negative element of the array:

 int[] arr = new int[10]; arr[-1] = 1; //ошибка, Π½Π΅Ρ‚ элСмСнта -1 

either to the element beyond the top of the array

 int[] arr = new int[10]; arr[10] = 1; //ошибка, Π½Π΅Ρ‚ элСмСнта 10 

In this case, an incorrect index is indicated in the error message:

java.lang.ArrayIndexOutOfBoundsException: 0

In this case, the length of the array is 0:

 int x = 0, y = 0; int Arr1[] = new int[x]; // x = 0 пустой массив 

Accordingly, it is impossible to refer to its elements, they are not. Try setting the length of the array.

  • after the length is set there will be a new error: java.lang.ArrayIndexOutOfBoundsException: 1, the problem is all in the same marked line, because the array indices start from zero - keekkenen
  • @keekkenen but that's another story :) - default locale
  • @keekkenen is looking at how long to set. I suppose with zero the author of the question was mistaken and the array should be of length n + 1, where n is the maximum number that will be tracked in it - default locale
  • the story may be different, but her legs grow from the same place and no matter what the author wanted to find there with this code - keekkenen
  • @keekkenen the bottom line is that if the author sets the length to 101, the error will not occur. - default locale