0

I want to ask something because I don't understand something. I want to found min element in array, when I use this code it is fine:

public static int najmanji(int[] niz) {
    int min = niz[0];
    for (int el = 0; el<niz.length; el++) {
        if (niz[el] < min) {
            niz[el] = min;
            return min;
        }
    }

    return min;

}

But when I use foreach loop I have exception ArrayIndexOutOfBoundsException.

public static int najmanji(int[] niz) {
    int min = niz[0];
    for (int el : niz){
        if (niz[el] < min) {
            niz[el] = min;
            return min;
        }
    }

    return min;
 }

Why I have this error? Because foreach is same like for loop?

dur
  • 15,689
  • 25
  • 79
  • 125
Blue Master
  • 61
  • 1
  • 6
  • 1
    [How to avoid java.lang.ArrayIndexOutOfBoundsException](http://stackoverflow.com/questions/32568261/how-to-avoid-java-lang-arrayindexoutofboundsexception) –  Sep 24 '15 at 00:37
  • @Blue Master also your min function is not returning min. Example:int[] datas1 = {5,6,7,8,4,3,2,1}; najmanji(datas1) would return 5, which is clearly not the min. Use this: public static int najmanji2(int[] niz){ int min=niz[0]; for(int el=0;el – alainlompo Sep 24 '15 at 00:41

1 Answers1

2

el does not represent an index; it's the actual value.

for(int i = 0; i < myArray.length; i++){
    int curVal = myArray[i];
    //your code...
}

Is the same as

for (int curVal : myArray){
    //your code...
}
Michael
  • 2,673
  • 1
  • 16
  • 27