java 數組的遍曆 異常

來源:互聯網
上載者:User

標籤: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 數組的遍曆 異常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.