reijatsu reijatsu - 1 month ago 5
Java Question

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20

I have an work for school, I need to make array using int type numbers.
I already assigned every value.
If i try to run it, it shows that there is - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20.

if (K==0) {
Random r = new Random();
for (i = 0; i < 20; i++)
A[i] = r.nextInt() * 100 - 50;
}
else {
for (i=0; i < 20; i++) { // It shows that problem is somewhere in
A[i] = A[i + 1] + K; // these 2 lines.
}
System.out.println("A:");
for (i = 0; i < 20; i++)

Answer

That means that you try to access A[20] even though it doesn't exist

When i equals 19, the following line becomes a problem:

A[i] = A[i + 1] + K;

Use 19 insead of 20 in your loop and it should be fine. You need to decide what to do with A[19] though, as it's value won't change.