JAVA/배열(array)
배열(array)_4
whale_it
2018. 8. 16. 21:22
3.1다차원 배열
- 2차원 이상의 배열
선언 방법 | 선언 예 |
---|---|
타입[][] 변수이름 | int [][] score |
타입 변수이름[][] | int score[][] |
타입[] 변수이름[] | int[] score[] |
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]
3.2 2차원 배열의 초기화
int[][] arr = new int[][]{{1,2,3},{4,5,6}}
int[][] arr = {{1,2,3},{4,5,6}}
국어 | 영어 | 수학 | |
---|---|---|---|
1 | 100 | 100 | 100 |
2 | 20 | 20 | 20 |
3 | 30 | 30 | 30 |
4 | 40 | 40 | 40 |
5 | 50 | 50 | 50 |
xxxxxxxxxx
package ch05;
class ArrayEx18 {
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]);
}
}
for (int[] tmp : score) {
for (int i : tmp) {
sum += i;
}
}
System.out.println("sum="+sum);
}
}
xxxxxxxxxx
package ch05;
class ArrayEx19 {
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;
int engTotal = 0;
int 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);
}
System.out.println("=============================");
System.out.printf("총점:%3d %4d %4d%n", korTotal, engTotal, mathTotal);
}
}
3.3 가변 배열
int[][] score = new int[5][]
score[0]= new int[4]
score[1]= new int[3]
score[2]= new int[2]
score[3]= new int[2]
score[4]= new int[3]
3.4 다차원 배열의 활용
단어맞추기
package ch05;
import java.util.*;
class MultiArrEx4{
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 scanner = 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 = scanner.nextLine();
if(tmp.equals(words[i][1])) {
System.out.printf("정답입니다.%n%n");
} else {
System.out.printf("틀렸습니다. 정답은 %s입니다.%n%n",words[i][1]);
}
} // for
} // main의 끝
}
이전글