ArrayoutOfBoundsException

Hi FreshlyChicken,

I can see that you tried to format your post but you didn’t use it correctly. Read this thread for more info: Guidelines—Tips on Asking Questions

Now to get back to your question, I’m not sure you really know what it means because the fix is quite obvious when you figured out where it is coming from. You are getting this error because you try to access an element of an array that does not exist because the array is too short.

In this case the bug is on this line:

if (randomZahl[i] == a)

You are using it in the following for loop:

for (int i = 0; i <= 25; ++i) {
  if (randomZahl[i] == a) {
    fill(0);
  }
}

You are making i going from 0 to 25 so at some point i will be 25 and thus you will be trying to access the 25th element of the randomZah array. But if we look at how you defined your array, we can see that it has only 5 elements:

int[] randomZahl = {3, 6, 8, 9, 4};

so you can only access element from index 0 to 5.

To cancel your errror you then only need to change your for loop to not exceed the size of your array:

for (int i = 0; i < 5; ++i) {
  if (randomZahl[i] == a) {
    fill(0);
  }
}

or even more fancy:

for (int i = 0; i < randomZahl.length; ++i) {
  if (randomZahl[i] == a) {
    fill(0);
  }
}
1 Like