使用 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