Lukasz Medza
Lukasz Medza

Reputation: 499

Java deal with array index out of bounds

I'm writing an algorithm that compares a number n with elements n+1 and n-1.

This means that the first and last check fail because array.length + 1 would be out of bounds and so would array[0-1]. I'm trying to find a way to stop the program from throwing the array index out of bounds exceptions but I am not sure how to do this. My initial plan was to check that array[0-1] and length+1 are always null like so:

numbers[x-1] == null

But this doesn't work because of a mismatch from int to null. Any ideas on how to remedy this would be very appreciated.

Upvotes: 1

Views: 4951

Answers (5)

SMA
SMA

Reputation: 37033

Something you could use to compare arrays with last and next element:

for(int index=1;index<array.length-1;index++){
    if (number > numbers[index - 1] && number < numbers[index + 1]) {
        System.out.println("Number is between " + (index - 1) + " and " + (index + 1));
    }
 }

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Iteration starts with index 1 and ends with index array.length - 1.

for(int i=1;i<array.length-1;i++){
   int prev = array[i-1];
   int current = array[i];
   int next = array[i+1];
}

Upvotes: 5

Eran
Eran

Reputation: 393846

I'd just a checks for the edges of the array :

int prev = -1;
int next = -1;
for (int i=0; i<array.length; i++) {
    if (i>0)
        prev = array[i-1];
    if (i < array.length - 1)
        next = array[i+1];
    else
        next = -1;
    // now do whatever you wish to do with array[i], prev and next
}

In that case I chose -1 to represent a "null" value. You can use something else, depending on the range of the values that can be in your array.

Upvotes: 1

morpheus05
morpheus05

Reputation: 4872

Besides the length checks the other answers suggest, you also could create the array one element bigger, so that the last element n+1 is still a valid array position but marks the end of the array. This way you can forget all the length checks which would improve the speed of your algorithm - if this is important. Otherwise I would implement a length check.

Upvotes: 0

Gil Moshayof
Gil Moshayof

Reputation: 16761

You should use "if" statements to check that your index is within the bounds:

if (x >= 0 && x < numbers.length)
    numbers[x] = someNumber

Upvotes: 0

Related Questions