본문 바로가기
JAVA

배열 생성, 초기화 및 접근 [코딩백과 with JAVA]

by GangDev 2024. 12. 21.

배열 생성, 초기화 및 접근

배열을 사용하려면 먼저 생성하고 초기화한 후에 접근해야 합니다. 이 과정을 자세히 살펴보겠습니다.

배열 생성

배열을 생성하는 방법은 두 가지가 있습니다:

  1. new 연산자 사용
int[] anArray = new int[10];

이 방법은 명시적으로 배열의 크기를 지정합니다. 만약 이 단계를 생략하면 컴파일러는 에러를 발생시킵니다.

  1. 초기값 목록 사용
int[] anArray = {
    100, 200, 300,
    400, 500, 600,
    700, 800, 900, 1000
};

이 방법은 배열을 선언하고 도시에 초기화합니다. 배열의 크기는 제공된 값의 개수로 자동으로 결정됩니다.

배열 초기화

배열을 생성한 후 각 요소에 값을 할당할 수 있스비다.

anArray[0] = 100;
anArray[1] = 200;
anArray[2] = 300;
// ...

또는 루프를 사용하여 초기화할 수 있습니다:

for (int i = 0; i < anArray.length; i++) {
    anArray[i] = i * 10;
}

배열 접근

배열의 요소에 접근하려면 인덱스를 사용합니다:

System.out.println("첫 번째 요소: " + anArray[0]);
System.out.println("두 번째 요소: " + anArray[1]);
System.out.println("세 번째 요소: " + anArray[2]);

인덱스는 0부터 시작하며, 마지막 유효 인덱스는 length - 1입니다.

다차원 배열

다차원 배열도 생성하고 초기화할 수 있습니다:

String[][] names = {
    {"Mr. ", "Mrs. ", "Ms. "},
    {"Smith", "Jones"}
};

// 접근 예시
System.out.println(names[0][0] + names[1][0]); // Mr. Smith
System.out.println(names[0][2] + names[1][1]); // Ms. Jones

Java의 다차원 배열은 각 요소가 배열인 배열입니다. 이는 C나 Fortran의 배열과는 다릅니다. 따라서 행의 길이가 달라도 됩니다.

배열 길이 확인

배열의 길이는 length 속성을 통해 얻을 수 있습니다:

int arrayLength = anArray.length;
System.out.println("배열의 길이: " + arrayLength);

배열 관련 주의사항

  1. 인덱스 범위: 유효한 인덱스의 범위를 초과하면 ArrayIndexOutOfBoundException이 발생합니다.
  2. 타입 일치: 배열의 타입과 할당하는 값의 타입이 일치해야 합니다.
  3. null 처리: 초기화되지 않은 배열 참조 변수는 null로 초기화됩니다.

배열 활용 예시

배열은 다양한 상황에서 유용하게 사용될 수 있습니다:

public class ArrayUsageExample {
    public static void main(String[] args) {
        // 1. 학생들의 이름과 점수 저장 및 처리
        String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Eve"};
        int[] studentScores = {85, 92, 78, 95, 88};

        // 평균 점수 계산
        double sum = 0;
        for (int score : studentScores) {
            sum += score;
        }
        double average = sum / studentScores.length;
        System.out.println("평균 점수: " + average);

        // 2. 최고 점수와 해당 학생 찾기
        int maxScore = Integer.MIN_VALUE;
        String topStudent = "";
        for (int i = 0; i < studentScores.length; i++) {
            if (studentScores[i] > maxScore) {
                maxScore = studentScores[i];
                topStudent = studentNames[i];
            }
        }
        System.out.println("최고 점수: " + maxScore + ", 최고 득점자: " + topStudent);

        // 3. 점수별 학생 분류
        String[] scoreCategories = new String[studentScores.length];
        for (int i = 0; i < studentScores.length; i++) {
            if (studentScores[i] >= 90) {
                scoreCategories[i] = "A";
            } else if (studentScores[i] >= 80) {
                scoreCategories[i] = "B";
            } else if (studentScores[i] >= 70) {
                scoreCategories[i] = "C";
            } else if (studentScores[i] >= 60) {
                scoreCategories[i] = "D";
            } else {
                scoreCategories[i] = "F";
            }
        }
        System.out.println("점수별 학생 분류:");
        for (int i = 0; i < studentNames.length; i++) {
            System.out.println(studentNames[i] + ": " + scoreCategories[i]);
        }

        // 4. 학생 이름 정렬
        Arrays.sort(studentNames);
        System.out.println("정렬된 학생 이름 목록:");
        for (String name : studentNames) {
            System.out.println(name);
        }

        // 5. 점수 통계 계산
        int[] scoreCounts = new int[101]; // 0부터 100까지 점수 카운트
        for (int score : studentScores) {
            scoreCounts[score]++;
        }
        System.out.println("점수 분포:");
        for (int i = 0; i < scoreCounts.length; i++) {
            if (scoreCounts[i] > 0) {
                System.out.println(i + "점: " + scoreCounts[i] + "명");
            }
        }
    }
}

편히 모아진 글 보시려면 아래 위키독스 링크 >>
https://wikidocs.net/book/17111