정렬
– 동일한 유형의 여러 변수를 선언할 때 사용되는 구문
– 배열을 선언할 때 배열의 크기는 선언 시점에 결정되어야 합니다..
– 배열 선언 후 각 변수를 방 번호로 설정(색인)~로 나누다.
– 배열의 인덱스입니다. 0 ~ 길이 -하나까지 있다. (문자열과 유사)
– 변수와 달리 배열은 처음 선언될 때 모든 공간 값을 초기화합니다..
(존재들 : 0, 실수 : 0, 부울 : 거짓, 참조 유형 : 영)
배열 선언
하나. 유형( ) 변수 이름 = 새로운 유형(크기);
2. 유형( ) 변수 이름 = { v1, v2, v3, v4, … };
삼. 유형( ) 변수 이름 = 새로운 유형() { v1, v2, v3, v4, … };
- 문자형 배열(문자열)
public class B13_Array {
public static void main(String() args) {
char() text = new char(15); // 문자 배열 (문자열)
text(0) = 'h';
text(1) = 'e';
text(2) = 'l';
text(3) = 'l';
text(4) = 'o';
text(5) = 0;
System.out.println(text);
}
}
- int형 배열
public class B13_Array {
public static void main(String() args) {
// int타입 변수를 1000개 선언하기
// 배열 크기가 1000일 때 인덱스는 0 ~ 999까지 존재한다.
int() a = new int(1000);
// ※ 초기화 하지 않은 변수는 사용할 수 없다.
int num;
// System.out.println(num);
// 배열에 값 넣기
a(0) = 5;
a(1) = 10;
a(2) = 99;
// 배열에 들어있는 값 꺼내 쓰기
System.out.println(a(0));
System.out.println(a(1));
System.out.println(a(555)); // 값을 넣은 적 없는 배열에는 0이 들어있다.
}
}
- 참조 유형의 배열
public class B13_Array {
public static void main(String() args) {
String() words =
{"apple", "banana", "kiwi", "mango", "grape", "melon"};
System.out.println(words(0));
System.out.println(words(1));
System.out.println(words(2));
}
}
배열 루프
public class B13_Array {
public static void main(String() args) {
// 배열은 반복문과 함께 사용하기 아주 좋은 형태로 되어있다.
for (int i = 0; i < words.length; ++i) {
System.out.println(words(i));
}
}
}
유형별 초기값
public class B13_Array {
public static void main(String() args) {
// boolean의 초기값 : false
boolean() passExam = new boolean(30);
System.out.println(passExam(7));
// 참조형의 초기값 : null
String() snacks = new String(10);
System.out.println(snacks(5));
String() animals = new String() {"cat", "dog", "lion"};
System.out.println(animals(2));
}
}
}
퀴즈
1위 100위개 점수(0가리키다 ~100가리키다)무작위로 생성되어 배열에 저장됨
2. 한 줄의 배열에 저장된 값 10각각 에디션 (60미만 포인트 엑스표시)
삼. 모든 등급의 평균 반환 (소수점 이하 두 자리까지 출력)
4. 최고점수와 최저점수 출력
답변
package quiz;
public class B13_RandomScore {
/*
1. 100개의 점수(0점 ~ 100점)를 랜덤으로 생성하여 배열에 저장
2. 배열에 저장된 값을 한 줄에 10개씩 출력
(60점 미만인 점수는 X로 표시)
3. 모든 점수의 평균을 출력 (소수 둘째자리까지 출력)
4. 가장 높은 점수와 가장 낮은 점수를 출력
*/
public static void main(String() args) {
int() score = new int(100);
int count = 0;
int total = 0;
double average = 0;
int max = 0;
int min = 0;
for (int i = 0; i < score.length; ++i) {
// 1. 100개의 점수(0점 ~ 100점)를 랜덤으로 생성하여 배열에 저장
score(i) = (int)(Math.random() * 101);
++count;
// 2. 배열에 저장된 값을 한 줄에 10개씩 출력
if (score(i) < 60) {
System.out.printf("%d(%c)\t", score(i), 'X');
} else {
System.out.printf("%d\t", score(i));
}
if (count == 10) {
System.out.println();
count = 0;
}
total += score(i);
// 4. 가장 높은 점수와 가장 낮은 점수를 출력
min = score(0);
for (int j = 0; j < score.length; ++j) {
max = max > score(j) ? max : score(j);
min = min < score(j) ? min : score(j);
}
}
// 3. 모든 점수의 평균을 출력 (소수 둘째자리까지 출력)
average = total / 100.0;
System.out.printf("평균: %.2f\n", average);
System.out.println("최고점: " + max);
System.out.println("최하점: " + min);
}
}