範例:
- class java_ex34_array_for {
- public static void main(String[] args) {
- //使用 for 迴圈遍歷一維陣列
- int[] a = new int[5];
- a[0] = 66;
- a[1] = 99;
- a[2] = 67;
- a[3] = 75;
- a[4] = 89;
- System.out.println("一維陣列遍歷");
- for(int i=0;i<a.length;i++){
- System.out.println("a["+ i + "] = " + a[i]);
- }
- System.out.println("=====================================");
- //使用 for 迴圈遍歷二維陣列
- int[][] b = new int[2][3];
- b[0][0] = 1;
- b[0][1] = 2;
- b[0][2] = 3;
- b[1][0] = 4;
- b[1][1] = 5;
- b[1][2] = 6;
- System.out.println("二維陣列遍歷");
- for(int i=0;i<b.length;i++){
- for(int j=0;j<b[i].length;j++){
- System.out.println("b["+ i + "][" + j + "] = " + b[i][j]);
- }
- }
- }
- }
執行結果: