본문 바로가기
Backend/JAVA_Basic

08. JAVA, 배열 (array, 1차원 배열, 2차원 배열) & 연습문제

by 개발개발빈이 2022. 5. 30.

○ 배열 Array

    - 연속성 자료형, 열거형
    - 하나의 변수에 1개 이상의 동일한 자료형의 값을 저장할 수 있는 공간
    - element, 요소
    - index, 순서, 색인 (0부터 시작해서 1씩 증가한다)
    - 배열의 종류

        ① 1차원 배열 : [열]

        ② 2차원 배열 : [행][열]

        ③ 3차원 배열 : [면][행][열] → JAVA에는 없는 문법

    - new 연산자 : 메모리 할당(확보) 연산자

                        JAVA에서는 배열을 만드려면 메모리를 미리 할당해놓아야 함


    - JAVA와 JavaScript의 배열 비교

 

12. JavaScript 배열(Array)

○ Array (배열)   - 연속성 자료형, 열거형, 컬렉션     - 하나의 변수에 1개 이상의 값을 저장할 수 있는 공간     - element, 요소, 원소     - index, 순서, 색인 (0부터 ..

binscode.tistory.com

 

○ 1차원 배열

    - 배열선언 형식 : 자료형[] 배열이름=new 자료형[할당할 메모리(배열 요소의 개수)];

    - 배열 요소 개수 확인 : 배열이름.length

int[] kor=new int[3];   //4byte*3개 → 12바이트 메모리 할당
kor[0]=10;
kor[1]=30;
kor[2]=50;

System.out.println(kor[0]);	//10
System.out.println(kor[1]);	//30
System.out.println(kor[2]);	//50

System.out.println(kor[3]);  //ArrayIndexOutOfBoundsException 발생
                             //kor의 3번째 요소는 존재하지 않음

System.out.println(kor.length); //3 : kor배열 요소의 개수

 

    - 메모리 할당과 초기값 지정을 동시에 할 수 있다 (형식: 자료형[] 배열이름={요소1, 요소2, ...};

int[] eng= {20, 40, 60};  //메모리 할당 및 초기값 지정

for(int i=0; i<eng.length; i++) { //반복문 이용해서 배열 요소 모두 출력
System.out.println(eng[i]);
}//for end


double[] aver= {1.2, 3.4, 5.6};

char[] ch= {'H', 'e', 'l', 'l', 'o'};

String[] name= {"개나리", "무궁화", "진달래"};

    

○ 2차원 배열

    - 2차원 배열 : [행][열]

    - 배열선언 형식 : 자료형[][] 배열이름=new 자료형[행 개수][열 개수];

int[][] kor=new int[2][3];  //2행 3열: 4바이트*6개 → 24바이트 메모리 할당
kor[0][0]=10;
kor[0][1]=20;
kor[0][2]=30;
kor[1][0]=40;
kor[1][1]=50;
kor[1][2]=60;

for(int r=0; r<=1; r++) {
    for(int c=0; c<=2; c++) {
        System.out.println(kor[r][c]);
    }//for end
}//for end

 

    - 행 개수 확인 : 배열이름.length

    - 열 개수 확인 : 배열이름[행번호].length

System.out.println(kor.length);      //2 → kor배열의 행의 개수
System.out.println(kor[0].length);   //3 → kor[0]행의 열의 개수
System.out.println(kor[1].length);   //3 → kor[1]행의 열의 개수

for(int r=0; r<kor.length; r++) {
    for(int c=0; c<kor[0].length; c++) {//행개수, 열개수 이용해서 kor배열 전체 출력
        System.out.println(kor[r][c]);
    }//for end
}//for end


System.out.println(kor[4][4]);   //lang.ArrayIndexOutOfBoundsException 발생
                                 //kor의 4행 4열은 존재하지 않음


    -  2차원 배열에서 각 행의 열의 개수는 달라도 된다

int[][] eng= {
                 {10,20}
                ,{30,40,50,60}
                ,{70,80,90}
             };

System.out.println(eng.length);     // 3
System.out.println(eng[0].length);  // 2
System.out.println(eng[1].length);  // 4
System.out.println(eng[2].length);  // 3

int row=eng.length;
for(int r=0; r<row; r++) {
    int col=eng[r].length;
    for(int c=0; c<col; c++) {
        System.out.print(eng[r][c] + " ");
    }//for end
    System.out.println();
}//for end

 

○ 배열 정렬

    - Arrays.sort(lotto);

int[] lotto= {3, 7, 4, 15, 28, 13};

Arrays.sort(lotto);	//1차원 배열을 전달하면 오름차순 정렬

for(int i=0; i<lotto.length; i++) {
    System.out.println(lotto[i]);
}//for end

 

● Practice 연습문제

    - 배열 관련 연습문제

    - Q1~Q3 주어진 배열

char[] ch= {'S', 'o', 'l', 'D', 'E', 'S', 'K'};
int size=ch.length;

 

        Q1) 대, 소문자의 개수를 각각 구하시오

//Q1
int uppercnt = 0;
int lowercnt = 0;

for(int i=0; i<size; i++) {
    if(ch[i]>='A' && ch[i]<='Z') {
        uppercnt++;
    }else if(ch[i]>='a' && ch[i]<='z') {
        lowercnt++;
    }//if end
}//for end

System.out.printf("대문자: %d개, 소문자: %d개 \n", uppercnt, lowercnt);


////강사님 코드////////////////////////////////////////////////////////
    int upper=0, lower=0;
    for(int i=0; i<size; i++) {
        if(ch[i]>='A' && ch[i]<='Z') {upper++;}
        if(ch[i]>='a' && ch[i]<='z') {lower++;}
    }

    System.out.printf("대문자 개수: %d개 \n", upper);
    System.out.printf("소문자 개수: %d개 \n", lower);

 

        Q2) 대, 소문자를 서로 바꿔서 출력하시오

//Q2
for(int i=0; i<size; i++) {
    if(ch[i]>='A' && ch[i]<='Z') {
        ch[i]=(char)(ch[i]+32);
    }else if(ch[i]>='a' && ch[i]<='z') {
        ch[i]=(char)(ch[i]-32);
    }//if end
    System.out.print(ch[i]);
}//for end


////강사님 코드////////////////////////////////////////////////////////
    for(int i=0; i<size; i++) {
        if(ch[i]>='A' && ch[i]<='Z') {System.out.printf("%c", ch[i]+32);}
        if(ch[i]>='a' && ch[i]<='z') {System.out.printf("%c", ch[i]-32);}
    }//for end

 

        Q3) 모음의 개수를 구하시오 (AEIOUaeiou)

//Q3
char[] vowel= {'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'};
int vwsize=vowel.length, vwcnt=0 ;

for(int i=0; i<size; i++) {
    for(int j=0; j<vwsize; j++) {
        if(ch[i]==vowel[j]) {
            vwcnt++;
        }//if end
    }//for end
}//for end


////강사님 코드////////////////////////////////////////////////////////
    int mo=0;
    for(int i=0; i<size; i++) {
        char c=ch[i];
        if(c>='A' && c<='Z') {
            c=(char)(c+32);  //모두 소문자로 만듬 
        }//if end

        switch(c) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u': mo++;
        }//switch end
        
    }//for end

    System.out.printf("모음의 개수 %d\n", mo);

 

        Q4) 각 행의 모음의 개수를 구하시오

//주어진 배열
char[][] name= {
                 {'H', 'a', 'p', 'p', 'y'}
                ,{'A', 'p', 'p', 'l', 'e'}
                ,{'H', 'e', 'l', 'l', 'o'}
             };
int row=name.length;

//Q4
int col=name[0].length;
int vcount=0;

for(int r=0; r<row; r++) {
    for(int c=0; c<col; c++) {
        for(int v=0; v<vwsize; v++) {
            if(name[r][c]==vowel[v]) {
                vcount++;
            }//if end
        }//for end
    }//for end
    System.out.printf("name[%d]행 : %d개 \n", r, vcount);
    vcount=0;			
}//for end


////강사님 코드////////////////////////////////////////////////////////
    int count = 0;

    for(int i=0; i<row; i++) {
        int coln=name[i].length;
        for(int j=0; j<coln; j++) {
            char c=name[i][j];
            if(c>='A' && c<='Z') {
                c=(char)(c+32);
            }//if end

            switch(c) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u': count++;
            }//switch end
        }//for end
        System.out.printf("name[%d]행 모음의 개수 : %d\n", i, count);
        count=0;
    }//for end

 

        Q5) 대각선 방향의 각 요소의 합을 구하시오

              대각선 ↘ 방향의 합 (4+9+7) / 대각선 ↗ 방향의 합 (2+9+6)

//주어진 배열
int[][] num= {
                 {4, 3, 2}
                ,{5, 9, 1}
                ,{6, 8, 7}
             };

//Q5
int rnum=num.length;
int cnum=num[0].length;

int downward=0, upward=0;

for(int r=0; r<rnum; r++) {
    for(int c=0; c<cnum; c++) {
        if(c==r) {
            downward=downward+num[r][c];
        }//if end
        if(r+c==rnum-1) {
            upward=upward+num[r][c];
        }//if end
    }//for end
}//for end

System.out.printf("대각선 ↘ 방향의 합 : %d\n", downward);
System.out.printf("대각선 ↗ 방향의 합 : %d\n", upward);


////강사님 코드////////////////////////////////////////////////////////

    // 대각선 ↘ 방향의 합 (4+9+7) num[0][0] + num[1][1] + num[2][2]
    // 대각선 ↗ 방향의 합 (2+9+6) num[0][2] + num[1][1] + num[2][0]

    int hap1=0;  // ↘ 방향
    int hap2=0;	 // ↗ 방향

    for(int i=0; i<num.length; i++) {
        hap1=hap1+num[i][i];
        hap2=hap2+num[i][num.length-1-i];
        }

    System.out.printf("대각선 ↘ 방향의 합 : %d\n", hap1);
    System.out.printf("대각선 ↗ 방향의 합 : %d\n", hap2);

 

댓글