2015-09-24 106 views
0

我想問一些問題,因爲我不明白。 我想找到分鐘元素數組,當我使用此代碼是罰款:Array異常ArrayIndexOutOfBoundsException

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; 

} 

但是當我使用foreach循環我有例外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; 
} 

爲什麼我有這個錯誤?因爲foreachfor循環相同嗎?

+1

[如何避免java.lang.ArrayIndexOutOfBoundsException(http://stackoverflow.com/questions/32568261/how-to-avoid-java-lang- arrayindexoutofboundsexception) –

+0

@藍色大師也是你最小的功能沒有返回分鐘。例如:int [] datas1 = {5,6,7,8,4,3,2,1}; najmanji(datas1)會返回5,這顯然不是最小值。使用這個:public static int najmanji2(int [] niz){ \t int min = niz [0]; (niz [el] alainlompo

回答

2

el不代表索引;這是實際的價值。

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

相同

for (int curVal : myArray){ 
    //your code... 
} 
相關問題