0

I have this method call from main:

exercise.SmallestOf(new int[] {2,9,6,4,8,34,2,15,81})

this is what the method does:

public int SmallestOf(int[] collection) {
    int min = 0;
    for(int i:collection) {
        if (collection[i]<min)
            min = collection[i];
    }
    return min;
}

I get a ArrayIndexOutOfBoundsException error at runtime. I assume there is something wrong with this:

new int[] {2,9,6,4,8,34,2,15,81}

I know I can do this:

int[] c = new int[] {2,9,6,4,8,34,2,15,81}
exercise.SmallestOf(c)

but I still want to know: what happens in the back that generates the error?

Daniel
  • 372
  • 2
  • 12
  • 1
    You are mixing up things here. Either you use "for-each" loops where you directly loop over the content (as your code is doing), or you should be using a "counting" for loop where your code provides the index variable to use. You are already accessing the content ... and then use it as index. That only "not fails" when all array content happens to be within (0, array.length - 1 ). – GhostCat Jun 27 '18 at 09:20
  • Foreach loop use object of your collection not index. So your code should look like this: if (i – Ivan Kaloyanov Jun 27 '18 at 09:22
  • When you write `for(int i:collection)` **i** contains the elements of collections ( i.e. its not a counter. ) instead of doing it collection[i] you have to use i directly. public int SmallestOf(int[] collection) { int min = 0; for(int i:collection) { if (i – Ashu Jun 27 '18 at 09:25
  • thanks @Ashu - (so there was no strange problem behind, just wrong code from me) – Daniel Jun 27 '18 at 09:36
  • actually you were treating elements as index, that's an issue. – Ashu Jun 27 '18 at 09:40

0 Answers0