在 Java 程式設計中列印二維陣列或矩陣


在這篇文章中,我們將嘗試列印一個數字陣列或矩陣到控制檯,就像我們通常寫在紙上的方式。

為此,邏輯是一次訪問陣列的每個元素,並使它們以空格分隔列印,當行在矩陣中到達末端時,我們還將改變行

示例

現場演示

public class Print2DArray {
   public static void main(String[] args) {
   
      final int[][] matrix = {
         { 1, 2, 3 },
         { 4, 5, 6 },
         { 7, 8, 9 }
      };
      for (int i = 0; i < matrix.length; i++) { //this equals to the row in our matrix.
         for (int j = 0; j < matrix[i].length; j++) { //this equals to the column in each row.
            System.out.print(matrix[i][j] + " ");
         }
         System.out.println(); //change line on console as row comes to end in the matrix.
      }
   }
}

輸出

1 2 3 
4 5 6 
7 8 9 

更新於: 2019 年 7 月 30 日

1,000 多次瀏覽

開啟職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.