/ JAVAJUNGSUK

Ch5-21~23. 2차원 배열 예제

자바의 정석 기초편

0. 목차



Chapter5. 배열

Ch5 - 21. 2차원 배열의 초기화 예제1

Ch5 - 22. 2차원 배열의 초기화 예제2

Ch5 - 23. 2차원 배열의 초기화 예제3



Ch5 - 21. 2차원 배열의 초기화 예제1


▶ 2차원 배열의 모든 값 더하기

▷ 변수 sum에 더한 값 저장
▷ 2차원 배열의 값을 모두 꺼내려면, 이중 for문 이용
int[][] score = {
                {100, 100, 100}
                , {20, 20, 20}
                , {30, 30, 30}
                , {40, 40, 40}  
                };

int sum = 0;

for (int i = 0; i < score.length; i++) {
    for (int j = 0; j < score[i].length; j++) {
        System.out.printf("score[%d][%d] = %d\n", i, j, score[i][j]);
        
        sum += score[i][j];
    }
    System.out.println("---");
}
System.out.println("sum = " + sum);

// console
score[0][0] = 100
score[0][1] = 100
score[0][2] = 100
---
score[1][0] = 20
score[1][1] = 20
score[1][2] = 20
---
score[2][0] = 30
score[2][1] = 30
score[2][2] = 30
---
score[3][0] = 40
score[3][1] = 40
score[3][2] = 40
---
sum = 570



Ch5 - 22. 2차원 배열의 초기화 예제2


▶ 국, 영, 수 성적의 총점과 평균값 구하기

▷ 번호별 국, 영, 수 성적 총점 구하기
▷ 번호별 국, 영, 수 성적 평균 구하기
int[][] score = {
                {100, 100, 100}
                , {20, 20, 20}
                , {30, 30, 30}
                , {40, 40, 40}  
                };
		
int sum = 0;

for (int i = 0; i < score.length; i++) {
    System.out.println("번호 " + (i + 1));
    System.out.printf("%s %s %s\n", "국어", "수학", "영어");
    
    for (int j = 0; j < score[i].length; j++) {
        System.out.printf("%3d ", score[i][j]);
        
        sum += score[i][j];
    }
    System.out.printf("\n총점 %d", sum);
    System.out.printf("\n평균 %f", sum/(float)score[i].length);
    System.out.printf("\n---\n");
}
System.out.println("전체 총점 = " + sum);

// console
번호 1
국어 수학 영어
100 100 100 
총점 300
평균 100.000000
---
번호 2
국어 수학 영어
 20  20  20 
총점 360
평균 120.000000
---
번호 3
국어 수학 영어
 30  30  30 
총점 450
평균 150.000000
---
번호 4
국어 수학 영어
 40  40  40 
총점 570
평균 190.000000
---
전체 총점 = 570



Ch5 - 23. 2차원 배열의 초기화 예제3


▶ 퀴즈

▷ 배열의 인덱스 이용
String[][] question = { { "cup", "컵" }, { "integer", "정수" }, { "cat", "고양이" }, { "angel", "천사" } };

Scanner scanner = new Scanner(System.in);

for (int i = 0; i < question.length; i++) {

    System.out.printf("Q%d. %s의 뜻은? \n> ", (i + 1), question[i][0]);
    String inputString = scanner.nextLine();
    
    if (inputString.equals(question[i][1])) {
        System.out.printf("정답!\n\n");
    } else {
        System.out.println("오답!");
        System.out.printf("정답은 %s\n\n", question[i][1]);
    }
}

// console
Q1. cup 뜻은?
> cup
오답!
정답은 

Q2. integer 뜻은?
> 정수
정답!

Q3. cat 뜻은?
> 고양이
정답!

Q4. angel 뜻은?
> 1004
오답!
정답은 천사