0

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)

  • 2
    Just change it to i < array.length. – dsp_user Sep 22 '16 at 10:24
  • 1
    As an aside, now would be a good time to get into the habit of declaring variables at the point of first use, rather than all of them at the top of the method - and initialize at the point of declaration, e.g. `int[] array = new int[5];` or better yet `int[] array = { 4, 7, 13, 29, 5 };` – Jon Skeet Sep 22 '16 at 10:25
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – default locale Sep 22 '16 at 10:38

4 Answers4

1

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

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
porgo
  • 1,729
  • 2
  • 17
  • 26
0

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.

djointster
  • 346
  • 3
  • 12
  • 1
    Probably you can remove from the answer the line of code that populates the array, this will make your answer clearer ;) – acornagl Sep 22 '16 at 10:33
0

change

i <= array.length

to

i < array.length

or

i <= (array.length-1)

Index starts from 0 onward till length-1

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78