Java 遍歷數組

1.用for循環遍歷數組

public class text01 {
    public static void main(String[] args) {
        int[] arr = { 11, 24, 9, 16, 25 };
        for (int i=0; i<arr.length; i++) {//	for (int i = arr.length-1;i>=0;i--)倒序輸出
            int n = arr[i];
            System.out.println(n);
        }
    }
}

輸出
11
24
9
16
25


2.增強型for循環

  for(元素類型  元素名稱 : 遍歷數組(集合)(或者能進行迭代的)){

      語句

     }
 變量n直接拿到arr數組的元素
public class text02 {
    public static void main(String[] args) {
        int[] arr = { 11, 24, 9, 16, 25 };
        for (int n : arr) {
            System.out.println(n);
        }
    }
}
輸出
11
24
9
16
25

在for (int n : arr)循環中,變量n直接拿到ns數組的元素,而不是索引。

增強型for循環更加簡潔。但是,增強型for循環無法拿到數組的索引。

3.Arrays.toString(),快速打印數組

import java.util.Arrays;
public class text03 {
    public static void main(String[] args) {
       int[] arr = { 11, 24, 9, 16, 25 };
        System.out.println(Arrays.toString(arr));
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章