● 2차원 배열
- 배열 안에 배열
- 1차원 배열을 여러 개 선언할 때 관리하기 힘들기 때문에 2차원 배열을 한 번 선언한다.
※ 2차원 이상의 배열은 메모리 낭비가 심하므로 선호하지 않는다.
● 2차원 배열 선언
- 자료형[][] 배열명 = {{값1, 값2, ...}, {값3, 값4, ...}};
- 자료형[][] 배열명 = new 자료형[행][열];
- 자료형[][] 배열명 = null;
배열명 = new 자료형[행][열];
(ex) int[][] arrData = new int[2][3];

실습(2차원 배열)
1. 2치원 배열의 길이 출력
public class ArrTest {
public static void main(String[] args) {
int[][] arrData = {
{3, 4, 5, 6},
{8, 9, 0, 9},
{1, 2, 3, 4}
};
System.out.println(arrData.length); // 행의 길이
System.out.println(arrData[0].length); // 열의 길이
int length = arrData.length * arrData[0].length; // 전체 길이 = 행의 길이 * 열의 길이
System.out.println(length); // 전체 길이
}
}

2. 2차원 배열의 모든 값 출력하기
- 이중 for문 사용
public class ArrTest {
public static void main(String[] args) {
int[][] arrData = {
{3, 4, 5, 6},
{8, 9, 0, 9},
{1, 2, 3, 4}
};
for (int i = 0; i < arrData.length; i++) { // 행
for (int j = 0; j < arrData[i].length; j++) { // 열
System.out.print(arrData[i][j] + " ");
}
System.out.println();
}
}
}

※ for문과 if문 사용
public class ArrTest {
public static void main(String[] args) {
int[][] arrData = {
{3, 4, 5, 6},
{8, 9, 0, 9},
{1, 2, 3, 4}
};
for (int i = 0; i < length; i++) {
System.out.print(arrData[i / 4][i % 4] + " ");
if((i + 1) % 4 == 0) {
System.out.println();
}
}
}
}
3. 1부터 12까지 각 방에 순서대로 대입한다.(이중 for문을 사용해서 해결한다.)
public class ArrTest {
public static void main(String[] args) {
int[][] arrData = {
{3, 4, 5, 6},
{8, 9, 0, 9},
{1, 2, 3, 4}
};
int count = 0;
for (int i = 0; i < arrData.length; i++) {
for (int j = 0; j < arrData[i].length; j++) {
arrData[i][j] = ++count;
//%02d : 두 자리수로 간격을 맞춰주고, 두 자리수가 아니라면 앞에 0을 붙여준다.
System.out.printf("%02d ", arrData[i][j]);
}
System.out.println();
}
}
}

실습(CodeUp)
1. 1096
문제 설명
바둑판(19 * 19)에 n개의 흰 돌을 놓는다고 할 때,
n개의 흰 돌이 놓인 위치를 출력하는 프로그램을 작성해보자.
입력
바둑판에 올려 놓을 흰 돌의 개수(n)가 첫 줄에 입력된다.
둘째 줄 부터 n+1 번째 줄까지 힌 돌을 놓을 좌표(x, y)가 n줄 입력된다.
n은 10이하의 자연수이고 x, y 좌표는 1 ~ 19 까지이며, 같은 좌표는 입력되지 않는다.
출력
흰 돌이 올려진 바둑판의 상황을 출력한다.
흰 돌이 있는 위치는 1, 없는 곳은 0으로 출력한다.
내 풀이
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] ba = new int[20][20];
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
ba[x][y] = 1;
}
for (int i = 1; i < ba.length; i++) {
for (int j = 1; j < ba.length; j++) {
System.out.print(ba[i][j] + " ");
}
System.out.println();
}
}
}
2차원 배열을 이용한다.
'ETC > 복습' 카테고리의 다른 글
[복습_JAVA] 19 (0) | 2022.08.30 |
---|---|
[복습_JAVA] 18 (0) | 2022.08.28 |
[복습_JAVA] 16 (0) | 2022.08.25 |
[복습_JAVA] 15 (0) | 2022.08.22 |
[복습_JAVA] 14 (0) | 2022.08.21 |