在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP