標籤:col log for 超出 sys class null 指標異常 max 大數
在運算元組時,經常需要依次訪問數組中的每個元素,這種操作稱作數組的遍曆
1 public class ArrayDemo04 {2 public static void main(String[] args) {3 int[] arr = { 1, 2, 3, 4, 5 }; // 定義數組4 // 使用for迴圈遍曆數組的元素5 for (int i = 0; i < arr.length; i++) {6 System.out.println(arr[i]); // 通過索引訪問元素7 }8 }9 }數組的常見問題
數組的遍曆、最值的擷取、數組的排序
數組最值
在運算元組時,經常需要擷取數組中元素的最值
例:
1 public class ArrayDemo05 { 2 public static void main(String[] args) { 3 int[] arr = { 4, 1, 6, 3, 9, 8 }; // 定義一個數組 4 int max = arr[0]; // 定義變數max用於記住最大數,首先假設第一個元素為最大值 5 // 下面通過一個for迴圈遍曆數組中的元素 6 for (int x = 1; x < arr.length; x++) { 7 if (arr[x] > max) { // 比較 arr[x]的值是否大於max 8 max = arr[x]; // 條件成立,將arr[x]的值賦給max 9 }10 }11 System.out.println("max=" + max); // 列印最大值12 }13 }14 結果:最大值是9數組異常數組越界異常
在訪問數組的元素時,索引不能超出這個數組的範圍,否則程式會報錯
null 指標異常
在使用變數引用一個數組時,變數必須指向一個有效數組對象,如果該變數的值為null,則意味著沒有指向任何數組,此時通過該變數訪問數組的元素會出現null 指標異常
例:
1 public class ArrayDemo07 { 2 public static void main(String[] args) { 3 int[] arr = new int[3]; // 定義一個長度為3的數組 4 arr[0] = 5; // 為數組的第一個元素賦值 5 System.out.println("arr[0]=" + arr[0]); // 訪問數組的元素 6 arr = null; // 將變數arr置為null 7 System.out.println("arr[0]=" + arr[0]); // 訪問數組的元素 8 } 9 }10 結果:arr[0] =5;11 ........異常
java 數組的遍曆 異常