반응형
1차원 배열이 여러개 모인 것이 2차원 배열
int[][] score = new int[4][3];
score[0][0] = 100; // 배열 xocre의 1행 1열에 100을 저장
System.out.println(score[0][0]); // 배열 score의 1행 1열의 값을 출력
2차원 배열의 초기화
int[][] arr = new int[][] { {1,2,3},{4,5,6} };
int[][] arr = { {1,2,3},{4,5,6} }; // new int[][]가 생략됨 (주로 사용)
int[][] arr = {
{1,2,3},{4,5,6}
}; // 위와 동일하지만 보기가 쉬움
2차원 배열 예제
class Ex5_5 {
public static void main(String[] args) {
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("sum="+sum);
}
}
class Ex5_1_int {
public static void main(String[] args) {
int[][] score = {
{100,100,100}
,{20,20,20}
,{30,30,30}
,{40,40,40}
,{50,50,50}
};
// 과목별 총점
int korTotal = 0, engTotal = 0, mathTotal = 0;
System.out.println("번호 국어 영어 수학 총점 평균 ");
System.out.println("=============================");
for (int i = 0; i < score.length; i++) {
int sum = 0; // 개인별 총점
float avg = 0.0f; // 개인별 평균
korTotal += score[i][0];
engTotal += score[i][1];
mathTotal+= score[i][2];
System.out.printf("%3d",i+1);
for (int j = 0; j < score[i].length; j++) {
sum += score[i][j];
System.out.printf("%5d",score[i][j]);
}
avg = sum/(float)score[i].length; // 평균계산
System.out.printf("%5d %5.1f%n", sum, avg); // %5.1f = %5 : 총 5칸으로 .1f : 소수점 첫째 자리까지 표현
}
System.out.println("=============================");
System.out.printf("총점:%3d %4d %4d%n", korTotal, engTotal, mathTotal);
}
}
import java.util.Scanner;
class Ex5_2_int {
public static void main(String[] args) {
String[][] words = {
{"chair","의자"}, // words[0][0], words[0][1]
{"computer","컴퓨터"}, // words[1][0], words[1][1]
{"integer","정수"}, // words[2][0], words[2][1]
};
Scanner soff = new Scanner(System.in);
for (int i=0; i < words.length; i++) {
System.out.printf("Q%d. %s의 뜻은?", i+1, words[i][0]);
String tmp = soff.nextLine();
if (tmp.equals(words[i][1])) {
System.out.printf("정답입니다.%n%n");
} else {
System.out.printf("틀렸습니다. 정답은 %s입니다.%n%n",words[i][1]);
}
}
}
}
반응형
'java↗' 카테고리의 다른 글
java↗6-8. Arrays로 배열 다루기 (0) | 2024.03.22 |
---|---|
java↗6-7. String 클래스 (0) | 2024.03.22 |
java↗6-5. 커맨드 라인을 통해 입력받기 (0) | 2024.03.21 |
java↗6-4. String배열의 선언과 생성 (0) | 2024.03.21 |
java↗6-3. 배열의 활용 (0) | 2024.03.19 |