TIL/JAVA

[JAVA] 배열 Array

아람2 2024. 11. 8. 13:40
반응형

Chapter08 배열 Array 

수강 중인 인터넷 강의 

배열은 같은 타입의 변수를 사용하기 편하게 하나로 묶어둔 것 
배열을 사용하는 이유는 같은 타입의 변수를 반복해서 선언하고, 반복해서 사용하는 문제를 해결할 수 있다 

 

배열 생성 및 초기화

int[] students; 	//1. 배열 변수 선언 
students = new int[5]; //2. 배열 생성

배열을 사용하려면 int[] students; 와 같이 배열 변수를 선언한다

new int[5] 라고 입력하면 5개의 int 형 변수가 만들어진다

new 는 새로 생성한다는 뜻이고, int[5] 는 int 형 변수가 5개라는 뜻이다 

 

int[] students;
students = new int[]{90, 80, 70, 60, 50}; //배열 생성과 초기화
/* 또는 */
int[] students = new int[]{90, 80, 70, 60, 50}; //배열 변수 선언, 배열 생성과 초기화

배열 생성 간략 버전 

/* 배열 생성 간략 버전, 배열 선언과 함께 사용시 new int[] 생략 가능 */
int[] students = {90, 80, 70, 60, 50};

이건 안 됨!

/* 아래 줄만 봤을 때 int 형인지 몰라서 이렇게 하면 안 됨 */ 
int[] students;
students = {90, 80, 70, 60, 50};

배열 참조값 보관 

students = x001; // 배열 참조값 보관 

new int[5] 로 배열을 생성하면 배열의 크기만큼 메모리를 확보한다 - int 5개는 4 byte * 5 -> 20 byte 

배열을 생성하고 나면 자바가 메모리 어딘가에 이 배열에 접근할 수 있는 참조값 (주소)(x001) 을 반환하고

int[] students 에 생성된 배열의 참조값 (x001) 을 보관한다

이 참조값을 통해 배열을 참조할 수 있다, 즉, 참조값을 통해 메모리에 있는 실제 배열에 접근하고 사용할 수 있다

int[] students = new int[5]; 	//1. 배열 생성
int[] students = x001; 		//2. new int[5]의 결과로 x001 참조값 반환
students = x001 		//3. 최종 결과

인덱스 Index

배열의 위치를 나타내는 숫자 

new int[5] 와 같이 5개의 요소를 가지는 int 형 배열을 만들었다면 인덱스는 0, 1, 2, 3, 4 가 존재한다 

사용 가능한 인덱스의 범위는 0 ~ (n-1) 이 된다 

2차원 배열 

2차원 배열은 행과 열로 구성된다

2차원 배열 선언 및 생성 

/* arr[행][열], arr[row][column] */
int[][] arr = new int[2][3]

2차원 배열 예시 코드

package array;

public class ArrayDi1 {
    public static void main(String[] args) {
        /* 2x3 2차원 배열을 만들고, 값을 출력한다 */

        int[][] arr = new int[2][3];
        
        int i = 1;
        // 순서대로 1씩 증가하는 값을 입력한다
        for (int row = 0; row < arr.length; row++) {
        	for (int column = 0; column < arr[row].length; column++) {
            	arr[row][column] = i++;
            }
	}

        // 2차원 배열의 길이를 활용
        for (int row = 0; row < arr.length; row++) {
            for (int column = 0; column < arr[row].length; column++) {
                System.out.print(arr[row][column] + " ");
            }
            System.out.println();
        }
    }
}

arr.length 는 행의 길이 (arr 은 {}, {} 2개의 배열 요소를 가진다)

arr[row].length 는 열의 길이 

 

향상된 for문 

향상된 for 문 정의 

for (변수 : 배열 또는 컬렉션) {
// 배열 또는 컬렉션의 요소를 순회하면서 수행할 작업
}

배열의 인덱스를 사용하지 않고, 종료 조건을 주지 않아도, 해당 배열을 처음부터 끝까지 탐색한다 

: 의 왼쪽에 반복할 때마다 찾은 값을 저장할 변수를 선언하고, : 의 오른쪽에 탐색할 배열을 선택한다 

배열의 값을 하나씩 꺼내서 왼쪽에 담고 for문을 수행하면서, 배열의 끝에 도달해서 더 값이 없으면 for문이 종료된다 

배열의 인덱스를 사용하지 않고도 배열의 요소를 순회할 수 있기 때문에 코드가 간결하고 가독성이 좋다 

향상된 for 문 단축키 - iter 

향상된  for 문 예시

/* 향상된 for문, for-each문 */
for (int number : numbers) {
     System.out.println(number);
 }

향상된 for 문을 사용할 수 없을 때

향상된 for문에는 증가하는 인덱스 값이 감추어져 있기 때문에

int i 와 같이 증가하는 인덱스 값을 직접 사용해야 하는 경우는 사용할 수 없다 

/* for-each문을 사용할 수 없는 경우, 증가하는 index 값 필요할 때 */
for(int i = 0; i < numbers.length; ++i) {
	System.out.println("number" + i + "번의 결과는: " + numbers[i]); 
}
/* 증가하는 i 값을 출력해야 하므로 향상된 for 문 대신에 일반 for 문을 사용해야 한다 */

 

배열 예시 문제 #1

점수의 총합과 평균을 구하는 문제

package array.ex;

public class ArrayEx1 {
    public static void main(String[] args) {
        int[] students = {10, 20, 30, 40, 50};

        int total = 0;
        for (int i=0; i<students.length; i++){
            total += students[i];
        }
        System.out.println("총합 "+total);
        double average = (double) total / 5;
        System.out.println("평균 "+average);
    }
}

여기에서 for 문에 노란줄이 보이는데, 전구를 누르거나 Option+Enter 를 누르면

향상된 for 문으로 변경할래? 문구가 나온다 

/* 변경된 for 문 */
        for (int student : students) {
            total += student;
        }

 

배열 예시 문제 #2

사용자로부터 5개의 정수를 입력 받고, 역순으로 출력하는 문제

package array.ex;

import java.util.Scanner;

public class ArrayEx3 {
    public static void main(String[] args) {
        /* 사용자로부터 5개의 정수를 입력 받고, 역순으로 출력하는 문제 */
        Scanner scanner = new Scanner(System.in);

        System.out.println("5개의 정수를 입력하세요");
        int[] num = new int[5]; // 배열 선언
        for (int i = 0; i< num.length; i++){
            num[i] = scanner.nextInt();
        }

        System.out.println("역순으로 출력");
        for (int i = num.length-1; i >= 0; i--){
            System.out.print(num[i]);
            if (i > 0){
                System.out.print(", ");
            }
        }
    }
}

 

배열 예시 #3

학생들의 국어, 영어, 수학 점수를 2차원 배열로 입력 받고, 각 학생들의 총점과 평균을 계산하는 문제 

package array.ex;

import java.util.Scanner;

public class ArrayEx7 {
    public static void main(String[] args) {
        /* 학생들의 국어 영어 수학 점수를 2차원 배열로 입력 받고
         * 각 학생의 총점과 평균을 계산하는 문제 */
        /* 학생 수는 입력 받기 */

        Scanner scanner = new Scanner(System.in);
        System.out.print("학생 수를 입력하세요 ");
        int students = scanner.nextInt();

        /* 문자 배열로 과목 저장 */
        String[] subjects = {"국어", "영어", "수학"};

        /* 학생 별 점수를 저장할 배열 */
        int[][] scores = new int[students][subjects.length];

        /* 학생 별 총점을 저장할 배열 */
        int[] sum = new int[students];

        /* 학생 별 점수 입력 받기 */
        for(int i=0; i< students; i++){
            System.out.println((i+1)+"번 학생의 점수");
            for(int j=0; j< subjects.length; j++){
                System.out.print(subjects[j]+ " 점수 ");
                scores[i][j] = scanner.nextInt();
                sum[i] += scores[i][j];
            }
        }

        /* 학생 별 총점과 평균을 출력하기 */
        for(int i=0; i< students; i++){
            System.out.println((i+1)+"번 학생의 총점 "+sum[i]+" 평균 "+(double)sum[i]/subjects.length);
        }
    }
}

 

배열 예시 #4 

상품 관리 프로그램 - 상품 이름과 가격을 배열로 저장하여 출력하는 문제 

package array.ex;

import java.util.Scanner;

public class ProductAdminEx {
    public static void main(String[] args) {
        /* 상품 관리 프로그램 만들기
        * 상품 등록 - 상품 이름과 가격을 입력 받아 배열에 저장한다
        * 상품 목록 - 지금까지 등록한 모든 상품의 목록을 출력한다 */

        Scanner scanner = new Scanner(System.in);
        int maxProduct = 10;
        String[] productNames = new String[maxProduct];
        int[] productPrices = new int[maxProduct];
        int productCount = 0;

        while(true){
            System.out.println("1. 상품 등록 | 2. 상품 목록 | 3. 종료 ");
            System.out.print("메뉴를 선택하세요 ");
            int number = scanner.nextInt();
            scanner.nextLine(); /* Buffer 버리기 */

            if (number == 1) { /* 제약 사항 */
                if(productCount >= maxProduct){
                    System.out.println("MAX 초과 상품 등록 불가");
                    continue; /* 다시 While 문으로 이동 */
                }

                System.out.print("상품 이름 ");
                productNames[productCount] = scanner.nextLine();

                System.out.print("상품 가격 ");
                productPrices[productCount] = scanner.nextInt();

                productCount++;
            } else if (number == 2){
                for(int i=0; i< productCount; i++){
                    System.out.println(productNames[i]+" : "+productPrices[i]+"원");
                }
                productCount = 0; /* Count 초기화 */
            }
            else if(number == 3){
                System.out.println("프로그램이 종료됩니다");
                break;
            } else {
                System.out.println("숫자를 제대로 입력하세요");
            }
        }

    }
}
반응형

'TIL > JAVA' 카테고리의 다른 글

[JAVA] 변수와 초기화  (0) 2024.12.02
[JAVA] 기본형과 참조형  (2) 2024.11.26
[JAVA][기본] 클래스 Class  (4) 2024.11.16
[JAVA] 메서드 Method 2/2  (0) 2024.11.13
[JAVA] 메서드 Method 1/2  (0) 2024.11.12