배열(Array)이란
같은 타입의 여러 변수를 하나의 묶음으로 다루는 것
int score1, score2, score3, score4, score5;
int[] score = new int[5];
// 5개의 배열 생성. score[0], score[1], score[2], score[3], score[4]
인덱스의 범위는 0부터 배열길이-1까지
int[] score = new int[5];
score[0] = 100;
score[1] = 90;
score[2] = 80;
score[3] = 70;
score[4] = 60;
for (int i = 0; i <= 4; i++) {
System.out.println("score[" + i + "] 의 점수는 " + score[i]);
}
/* 출력 결과
score[0] 의 점수는 100
score[1] 의 점수는 90
score[2] 의 점수는 80
score[3] 의 점수는 70
score[4] 의 점수는 60
*/
배열이름.length
배열의 길이를 구하는 방법
int[] array = new int[5];
System.out.println(array.length); // 출력 결과 5
배열의 초기화
int[] score = new int[5];
score[0] = 100;
score[1] = 90;
score[2] = 80;
score[3] = 70;
score[4] = 60;
// 같은 결과
int[] score = new int[] {50, 60, 70, 80, 90};
String배열
String[] name = new String[3];
// 3개의 문자열을 담을 수 있는 배열 생성. 기본값은 null로 초기화
name[0] = "Kim";
name[1] = "Park";
name[2] = "Yi";
// 같은코드
String[] name = new String[]{"Kim", "Park", "Yi"};
// 같은코드
String[] name = {"Kim", "Park", "Yi"};
String 배열 초기화. new String[] 까지 생략하여 간단하게 사용할 수 있다.
public static void main(String[] args) {
String[] names = {"Kim", "Park", "Yi"};
for (int i = 0; i < names.length; i++)
System.out.println("names["+i+"] : " + names[i]);
names[0] = "Jung";
for (String str : names) // 향상된 for문
System.out.println(str);
}
String클래스의 주요 메서드
String str = "ABCDE";
char ch = str.CharAt(3); // 문자열 str 4번째 D를 ch에 저장
String str = "012345";
String tmp = str.substring(1, 4);
System.out.println(tmp); // 123 출력
String str = "abc";
if (str.equals("abc")) { // str이 abc와 같은지 확인
...
}
다차원 배열
int[][] score = new int[4][3]; 4행 3열의 2차원 배열 생성
| 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] |
2차원 배열 초기화
int[][] arr = { {1, 2, 3}, {4, 5, 6} };
예시
| 100 | 100 | 100 |
| 20 | 20 | 20 |
| 30 | 30 | 30 |
| 40 | 40 | 40 |
| 50 | 50 | 50 |
int[][] score = {
{100, 100, 100}
,{20, 20, 20}
,{30, 30, 30}
,{40, 40, 40}
,{50, 50, 50}
};'자바 > Java의 정석' 카테고리의 다른 글
| [Chapter 07] 객체지향 프로그래밍 II (2) | 2024.11.19 |
|---|---|
| [Chapter 06] 객체지향 프로그래밍 I (1) | 2024.11.19 |
| [Chapter 04] 조건문과 반복문 (1) | 2024.11.17 |
| [Chapter 3] 연산자 (1) | 2024.11.17 |
| [Chapter 02] 변수 variable (1) | 2024.11.17 |