question_mark
question_mark

Reputation: 31

Java: ArrayIndexOutOfBoundException when searching for an Integer value in an Array

If i am looking for a certain value (needle) in an arrary and the value doens't exit in this array I am getting an java.lang.ArrayIndexOutOfBoundsException. (see Code below) If the value exists in the array it works just fine.

It seems I am sitting already to long in front of my computer and i am already to blind to see the mistake, any help would be really appreciated. Thank you!

public static void main(String[] args) {
   int i = 0;
   int[] array;
   array = new int[5];
   int needle = 20; 
   boolean inarray;


   array[0] = 4;
   array[1] = 7;
   array[2] = 13;
   array[3] = 29;
   array[4] = 5;

    while (i <= array.length && needle != array[i]){
        i++;
    }
    inarray = !(i > array.length);
    System.out.println("value in array: " + inarray);

}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at test.Test.main(Test.java:33) C:\Users\admin\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds)

Upvotes: 0

Views: 76

Answers (4)

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

change

i <= array.length

to

i < array.length

or

i <= (array.length-1)

Index starts from 0 onward till length-1

Upvotes: 0

djointster
djointster

Reputation: 356

Your problem is in this line piece of code.

while (i <= array.length && needle != array[i]){
    i++;
}

As you have in your example, the first position of your array is the position 0 and the last is position 4. when you do array.length it returns 5. So your i <= array.length will evaluate to true when i=5, and will give you the exception you're having evaluationg array[i], because array[5] does not exist.

Instead of i <= array.length change your condition to i < array.length.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234695

Arrays in Java are zero based (Java ain't Fortran you know): array[0] is valid for an non-zero length array.

Change the fist part of your stopping condition to i < array.length.

Upvotes: 1

porgo
porgo

Reputation: 1737

array.length is 5 so when you are trying to get array[5] you get error. Just change

i <= array.length

to

i < array.length

Upvotes: 0

Related Questions