Java:使用3層for循環遍歷輸出三維數組內容。


使用三層循環遍歷多維數組

public class Ransack {
	public static void main(String[] args) {
		int array[][][] = new int[][][]{					// 創建並初始化數組
				{ { 1, 2, 3 }, { 4, 5, 6 } },
				{ { 7, 8, 9 }, { 10, 11, 12 } },
				{ { 13, 14, 15 }, { 16, 17, 18 } }
			};
		array[1][0][0] = 97;								// 改變指定數組元素
		for (int i = 0; i < array.length; i++) {			// 遍歷數組
			for (int j = 0; j < array[0].length; j++) {
				for (int k = 0; k < array[0][0].length; k++) {
					System.out.print(array[i][j][k] + "\t");
				}
				System.out.println();						// 輸出一維數組后換行
			}
		}
	}


使用foreach 遍歷三維數組

public class ForEachRansack {
	public static void main(String[] args) {
		int array[][][] = new int[][][]{					// 創建並初始化數組
				{ { 1, 2, 3 }, { 4, 5, 6 } },
				{ { 7, 8, 9 }, { 10, 11, 12 } },
				{ { 13, 14, 15 }, { 16, 17, 18 } }
			};
		for (int[][] is : array) {							// 遍歷數組
			for (int[] is2 : is) {
				for (int i : is2) {
					System.out.print(i + "\t");
				}
				System.out.println(); 						// 輸出一維數組后換行
			}
		}
	}
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM