Search code examples
javaarrayseclipseindexoutofboundsexception

Snippet of 1 Array to Check for Recurring Elements


I was working on using only 1 array and a nested for loop to check for repeated elements and turn them to 0. I have an IndexBound problem and can't quite tell what's wrong.

Any help?

    int data[] = new int[20];
    for(int i = 0; i < data.length; i++) {
        data[i] = in.nextInt();
    }
    for (int i = 0; i < 18; i++) {
        for (int x = i + 1; x < 20; i++) {
            if (data[i] == data[x]) {
                data[x] = 0;
            }
        }
    }


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at Arrays.Prog415h.main(Prog415h.java:47)
if (data[i] == data[x]) {

Solution

  • Here, the increment of the nested for loop is i instead of x. This means that i is overrunning the array bounds for every iteration by both the outer and inner loops. To resolve the issue, change it to:

    for (int x = i + 1; x < 20; x++)