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?

2
  • 1
    How to avoid java.lang.ArrayIndexOutOfBoundsException Commented Sep 24, 2015 at 0: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<niz.length;el++){ if(niz[el]<min){ min = niz[el]; } } return min; } Commented Sep 24, 2015 at 0:41

1 Answer 1

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...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.