陣列越界錯誤Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
阿新 • • 發佈:2022-03-18
題目:
判斷Largest函式是否有錯誤,嘗試列出錯誤資訊,給出解決方案
程式碼展示:
public class Main3 { public static void main(String[] args){ int[] array = {}; int length = 10; Largest(array,length); if(array!= null) { System.out.println("陣列為空"); }else if(length!=0){ System.out.println("Largest不執行"); }else{ System.out.println("輸出最大值"); } } private static int Largest(int list[], int length){ int i,max=0; for(i= 0; i< (length - 1); i++){ if(list[i]> max){ max=list[i];} } return max;} }
執行截圖:
解決思路:
陣列下標越界,假如陣列array的下標在遍歷過程中,實際上得到的是10,而得到的是比他下一位的數,即9,在陣列初始化的時候,也就是申請了九個陣列元素,這就會顯示陣列越界的錯誤,那麼問題出現在了哪裡呢
就是for迴圈在遍歷的過程中,for迴圈的終止判斷出現了問題,字元陣列的記憶體申請範圍是精確的,但是忽略了初始化為0的陣列空間,這也就是申請了九個,實際上有十個,陣列越界錯誤出現。