728x90

1. 2차원 배열의 선언과 인덱스

선언 방법 ex
타입[][] 변수이름;  int[][] score;
타입 변수이름[][]; int score[][];
타입[] 변수이름[]; int[] score[];

 

4행 3열의 2차원 배열을 만든다고 생각해보자

int[][] score = new int[4][3]; 

score[0][0] score[0][1] score[0][2]
score[1][0] score[1][1] score[1][2]
score[2][0] score[2][1] score[2][2]
score[3][0] score[3][1] score[3][2]

이렇게 4행 3열의 2차원 배열 score가 생성이 된다.

 

2. 2차원 배열의 초기화

2차원 배열도 괄호를{} 써서 생성과 초기화를 동시에 할 수 있다.

int[][] array = new int[][]{ {1, 2, 3}, {4, 5, 6} };
int[][] array = { {1, 2, 3}, {4, 5, 6} };//new int[][]가 생략 가능하다.

간단하게 한줄로 정렬해서 사용하는 것도 좋지만,

int[][] array = { 
		{1, 2, 3},
                  {4, 5, 6} 
                 };

이렇게 행을 구분하여 쓰면, 행별로 알아보기도 쉽다.

 

 

 

ex)학생 5명의 성적이 국어, 영어, 수학 순으로 score[][] 2차원 배열에 저장이 되어 있다. 이 다섯명의 점수를 출력하는 방법은?

public class Main {
    public static void main(String[] args) {

        int score[][] = {
                {100, 100, 100},
                {97, 88, 70},
                {92, 94, 69},
                {87, 89, 91},
                {100, 78, 93}
        };

        for(int i=0; i<score.length; i++){
            for (int j=0; j<score[i].length; j++){
                System.out.print(score[i][j]+" ");
            }
            System.out.println();
        }
    }
}
100 100 100 
97 88 70 
92 94 69 
87 89 91 
100 78 93

이렇게 출력이 된다.

 

ex) 그럼 5명 학생의 점수를 모두 더한다면?

public class Main {
    public static void main(String[] args) {

        int score[][] = {
                {100, 100, 100},
                {97, 88, 70},
                {92, 94, 69},
                {87, 89, 91},
                {100, 78, 93}
        };

        int sum = 0;
        for( int[] t : score){
            for (int i : t){
                sum += i;
            }
        }

        System.out.println(sum);
    }
}

 

 

 

3. 가변 배열

2차원 이상의 다차원 배열을 생성할 때 전체 배열 차수 중 마지막 차수 중 마지막 차수의 길이를 지정하지 않고, 추후에 각기 다른 길이의 배열을 생성함으로써 고정된 형태가 아닌 보다 유동적인 가변 배열을 구성할 수 있다.

예를 들어, 

int[][] score = new int[3][];
score[0] = new int[4];
score[1] = new int[2];
socre[2] = new int[3];
int score[][] = {
                {100, 100, 100, 34},
                {97, 88},
                {92, 94, 69},
        };

이렇게 사용이 가능하다.

728x90