Language/Java

배열

kalza 2018. 8. 26. 03:37

int a = 5;

int b = 3;

......

int c = 200;

위와 같이 수십,수백,수천,수만건의 데이터들을 다룰때 일일히 하나씩 변수를 만들어 담아 관리하는건 매우 비효율적일 것이다.

(정수형 데이터를 예로들었지만, 배열은 정수든, 실수든, 문자든, 문자열이 다 사용 가능하다.)


배열은 이러한 작업을 효율적으로 처리할 수 있도록 인덱스를 이용해서 같은 자료형의 데이터를 관리하는 것이다.

배열을 선언하고 처음 들어가는 값의 인덱스 주소는 0이 되기때문에 마지막 값의 인덱스는 n-1이 된다.


10개의 정수를 다루는 배열을 선언하면 아래와 같이 할 수 있다.

int[] array = int[10]

array[0] = 5; 

array[1] = 3;

......

array[9] = 2000;


배열은 어차피 같은 타입의 데이터들을 담기때문에 선언과 동시에 값을 대입 할 수 있다.

int[] array = {5,3,......,200};


지난 포스팅에서 다룬 특수 문자와 서식 문자를 사용하여 배열을 사용한 학사 관리 콘솔 프로그램을 짜본다.


                 // 문자열 데이터를 담는 배열을 생성과 동시에 초기화

                String[] name = {"박찬호", "이승엽", "박병호", "이병규", "류현진"};       

int[] score = new int[5];                                                             


    // Scanner 객체 생성

Scanner sc = new Scanner(System.in);


System.out.printf("%s의 점수를 입력하시오. : " , name[0]);

score[0] = sc.nextInt();

System.out.printf("%s의 점수를 입력하시오. : ", name[1]);

score[1] = sc.nextInt();

System.out.printf("%s의 점수를 입력하시오. : ", name[2]);

score[2] = sc.nextInt();

System.out.printf("%s의 점수를 입력하시오. : " , name[3]);

score[3] = sc.nextInt();

System.out.printf("%s의 점수를 입력하시오. : " , name[4]);

score[4] = sc.nextInt();

     // 실수형 표현을 위해 double형 명시적 형변환. 소수점 둘째자리까지 출력한다.

System.out.printf("%s 점수 : \t%.2f\n" ,  name[0], (double)score[0]);

System.out.printf("%s 점수 : \t%.2f\n" ,  name[1], (double)score[1]);

System.out.printf("%s 점수 : \t%.2f\n" ,  name[2], (double)score[2]);

System.out.printf("%s 점수 : \t%.2f\n" ,  name[3], (double)score[3]);

System.out.printf("%s 점수 : \t%.2f\n" ,  name[4], (double)score[4]);



double avg = (double)(score[0] + score[1] + score[2] + score[3] + score[4]) / 5;

System.out.printf("-----------------------\n 평 점 : \t%.2f", avg);

// 자원 반납. 객체를 닫아준다.

sc.close();