기본적인 사용법은 아래와 같다.
int[] array1 = {1, 2, 3};
int[][] array2 = {{1, 2, 3}, {4, 5, 6}};
int[][][] array3 = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
int[][] array2 = new int[2][3]; // 행 2개와 열 3개
int[] array1 = {1, 2, 3};
for (int el : array1) {
System.out.println(el);
}
int[][] array2 = {{1, 2, 3}, {4, 5, 6}};
for (int[] array1 : array2) {
for (int el : array1) {
System.out.print(el + " ");
}
}
// 1 2 3 4 5 6
int[][] array2 = new int[2][3];
for (int[] array1 : array2) {
for (int el : array1) {
System.out.print(el + " ");
}
}
// 0 0 0 0 0 0
3 x 3 행렬이 2차원 배열로 초기화 돼있다.
모든 원소를 1로 변경하고, 대각 원소는 10으로 변경하라.
int[][] testArray2 = new int[3][3];
for (int i = 0; i < testArray2.length; i++) {
for (int j = 0; j < testArray2[i].length; j++) {
if (i != j) {
testArray2[i][j] = 1;
} else {
testArray2[i][j] = 10;
}
System.out.print(testArray2[i][j] + " ");
}
System.out.println();
}