int[] score; // int 타입의 배열을 다루기 위한 참조변수 score 선언
score = new int[5]; // int 타입의 값 5개를 저장할 수 있는 배열 생성
int[] score = new int[5];
// 길이(length)가 5인 int 배열. 인덱스의 범위는 0~4까지.(0,1,2,3,4)
배열의 또 다른 장점 :
index로 상수 대신 변수 or 수식도 사용할 수 있다.for (int i=0; i <= 3; i++) { score[i] = i * 10; } // index로 상수 대신 변수 i를 사용하고, for문으로 변수 i의 값을 0~3까지 증가시킨다.
int[] arr = new int[5]; // 길이가 5인 int 배열
int tmp = arr.length; // arr.length의 값은 5이고 tmp에 5가 저장된다.
int[] score = new int[5];
for (int i=0; i < score.length; i++) {
System.out.println(score[i]);
int[] score = new int[]{ 50, 60, 70, 80, 90}; //배열의 생성과 초기화를 동시에!
int[] score = { 50, 60, 70, 80, 90)}; // new int[] 생략 가능
⭐️ 주의할 점 ⭐️
배열의 선언과 생성을 따로 하는 경우에는 new int[] 생략 불가!
int[] score;
score = { 50, 60, 70, 80, 90}; // 에러. new int[] 생략 불가
score = new int[]{ 50, 60, 70, 80, 90} // OK.
int[] iArr = { 100, 95, 89, 70, 60 };
System.out.println(Arrays.toString(iArr));
// [100, 95, 80,70, 60]이 출력된다.
String[] name = new String[3];
// 3개의 문자열을 담을 수 있는 배열을 생성한다.
int[][] score = new int[4][3]; // '배열이름[행index][열index]'
// 2차원 배열의 초기화 예제
public class Ex5_8 {
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.println("score["+i+"]["+j+"]");
sum += score[i][j];
}
}
System.out.println("sum = " + sum);
}
}
Chater 5
배열을 선언하거나 초기화한 것 중 잘못된 것과 그 이유는?
public class Quiz5_1 {
public static void main(String[] args) {
// 잘못된 것
// int[] arr[]; // 참조변수 이름이 없음.
// int[] arr = new int[5]{1,2,3,4,5}; // 괄호 안의 값의 개수에 의해 배열의 길이가 자동으로 결정되므로 배열 길이는 안 적어도 된다.
// int arr[5]; // 배열 선언과 동시에 생성하려면 연산자와 함께 배열의 타입과 길이를 지정해주어야 한다.
// 잘된 것
// int[] arr = {1, 2, 3};
// int[] arr = new int[5];
// int[] arr[] = new int[3][];
}
}
다음과 같은 배열이 있을 때, arr[3].length의 값은?
public class Quiz5_2 {
public static void main(String[] args) {
int[][] arr = {
{ 5, 5, 5, 5, 5},
{ 10, 10, 10},
{ 20, 20, 20, 20},
{ 30, 30}
};
// 4 ?
}
}
배열 arr에 담긴 모든 값을 더하는 프로그램을 완성하시오.
public class Quiz5_3 {
public static void main(String[] args) {
int[] arr = { 10, 20, 30, 40, 50};
int sum = 0;
for (int i=0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("sum = " + sum);
}
}
2차원 배열 arr에 담긴 모든 값의 총합과 평균을 구하는 프로그램을 완성하시오.
public class Quiz5_4 {
public static void main(String[] args) {
int[][] arr = {
{5, 5, 5, 5, 5},
{10, 10, 10, 10, 10},
{20, 20, 20, 20, 20},
{30, 30, 30, 30, 30}
};
int total = 0;
float average = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
total += arr[i][j];
}
}
average = (float) total / (arr.length * arr[0].length);
System.out.println("total = " + total);
System.out.println("average = " + average);
}
}
참고 도서 : 『JAVA의 정석 기초편』, 남궁 성, 도우출판