Nicholas Whitfield
Nicholas Whitfield

Reputation: 45

I need to find the values that are local minimums in this array, but I'm getting an arrayindexoutofbounds exception. How can I fix this?

public class LocalMinimum {
    public static void main(String[] args) {
        int[] A = {8, 5, 7, 2, 3, 0, 1, 9};
        for (int i = 0; i < A.length; ++i) {
            int prevValue = A[i - 1];
            int nextValue = A[i + 1];
            if ((A[i] < prevValue) && (A[i] < nextValue)) {
                System.out.println(A[i] + " is a minimum value.");
            }
            else {
                System.out.println(A[i] + " is not a minimum value.");
            }
        }
    }
}

The error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

Upvotes: 1

Views: 43

Answers (2)

Wojtek
Wojtek

Reputation: 1308

If you are writing

int prevValue = A[i - 1];
int nextValue = A[i + 1];

in the for loop, starting from i = 0 and ending with i = array.length - 1, be aware that at the first and last turn, you will be trying to get values from array[-1] and array[array.length] elements, which do not exist. Try starting the loop from 1 to array.length - 2:

for (int i = 1; i < array.length - 2; i++) {
    // do your job
}

Upvotes: 1

Leticia
Leticia

Reputation: 76

You should use module when trying to access A's itens so it never is out of bounds.

like:

int prevValue = A[((i - 1) % A.length)];
int nextValue = A[((i + 1) % A.length)];

This way, the result for the first iteration for prevValue will be the last number instead and the result for the last iteration for nextValue will be the first number.

Upvotes: 1

Related Questions