본문 바로가기
Web & Mobile/JAVA

Lecture 22 - Java(3)

by Bennyziio 2019. 4. 18.
반응형

배열 - Array
: 같은 타입의 여러 변수를 하나의 묶음으로 다루는 것을 '배열(Array)'이라고 한다. 많은 양의 데이터를 변수로 선언하기 힘들기 때문에 배열을 사용하여 같은 변수로 된 데이터들을 손쉽게 다룰 수 있다.

public class ArrayEx01 {
    public static void main(String[] args)
    {
        // 선언
        int[] arr1;
        int arr2[];

        // 생성
        arr1 = new int[5];

        // 초기화
        arr1[0] = 10;
        arr1[1] = 20;
        arr1[2] = 30;
        arr1[3] = 40;
        arr1[4] = 50;

        System.out.println(arr1[0]);
        System.out.println(arr1[4]);
    }
}

public class ArrayEx01 {
    public static void main(String[] args)
    {
        // 선언
        int[] arr1;
        int arr2[];

        // 생성
        arr1 = new int[5];

        // 초기화
        arr1[0] = 10;
        arr1[1] = 20;
        arr1[2] = 30;
        arr1[3] = 40;
        arr1[4] = 50;
        
        arr1[5] = 60;

        System.out.println(arr1[0]);
        System.out.println(arr1[4]);
    }
}

배열이 5개의 방만 만들었는데 6번째인 arr1[5]의 값을 입력하면 컴파일 시에는 오류가 없지만 실행시 런타임 에러가 난다

public class ArrayEx01 {
    public static void main(String[] args)
    {
        // 선언
        int[] arr1;
        int arr2[];

        // 생성
        arr1 = new int[5];

        // 초기화
        arr1[0] = 10;
        arr1[1] = 20;
        arr1[2] = 30;
        arr1[3] = 40;
        arr1[4] = 50;

        //arr1[5] = 60;

        System.out.println(arr1[0]);
        System.out.println(arr1[4]);
        System.out.println(arr1[5]);
    }
}

위와 반대의 경우로 5개의 방을 만들었는데 6번째 방 arr1[5]의 값을 읽어오려 하면 런타임 에러가 난다.

배열의 길이와 인덱스
생성된 배열의 각 저장공간을 '배열의 요소(element)'라고 하며, '배열이름[인덱스]'의 형식으로 배열의 요소에 접근한다. 인덱스(Index)는 배열의 요소마다 붙여진 일련번호로 각 요소를 구별하는데 사용된다.
"인덱스(index)의 범위는 0부터 '배열길이-1'까지."
배열의 길이 : 배열이름.length
배열의 길이는 int범위의 양의 정수(0도 포함) 이어야 한다.

public class ArrayEx01 {
    public static void main(String[] args)
    {
        // 선언
        int[] arr1;
        int arr2[];

        // 생성
        arr1 = new int[5];

        // 초기화
        arr1[0] = 10;
        arr1[1] = 20;
        arr1[2] = 30;
        arr1[3] = 40;
        arr1[4] = 50;

        //arr1[5] = 60;

        System.out.println(arr1[0]);
        System.out.println(arr1[4]);
        //System.out.println(arr1[5]);

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

배열의 길이 변경하기
배열의 길이를 변경하는 방법 :
1. 더 큰 배열을 새로 생성한다.
2. 기존 배열의 내용을 새로운 배열에 복사한다.
* 기존에 선언된 배열을 수정할 수는 없다.

배열 선언 / 생성 / 초기화

public class ArrayEx02 {
    public static void main(String[] args)
    {
        // 배열 선언 / 생성 / 초기화
        int[] arr1 = new int[5];    // 선언, 생성
        int[] arr2 = new int[] {10, 20, 30, 40, 50};    // 선언, 생성, 초기화
        int[] arr3 = {10, 20, 30, 40, 50};    // 선언, 생성, 초기화

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

향상된 for문(enhanced for statement)

public class ArrayEx02 {
    public static void main(String[] args)
    {
        // 배열 선언 / 생성 / 초기화
        int[] arr1 = new int[5];    // 선언, 생성
        int[] arr2 = new int[] {10, 20, 30, 40, 50};    // 선언, 생성, 초기화
        int[] arr3 = {10, 20, 30, 40, 50};    // 선언, 생성, 초기화

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

        for(int data : arr3) {
            System.out.println(data);
        }
    }
}

향상된 for문

배열의 활용
ArrayEx06 최대값과 최소값
커맨드 라인을 통해 입력받기

public class ArrayEx03 {
    public static void main(String[] args)
    {
        //System.out.println("배열의 길이 : " + args.length);

        for(String arg : args) {
            System.out.println("입력 값 : " + arg);
        }

        // 문자열 => 숫자로
        // Interger.parseInt() => 문자열을 숫자로 바꿔준다.
    }
}

향상된 for문으로 받는법

ArrayEx04 문자열을 숫자로 바꾸는 법

public class ArrayEx04 {
    public static void main(String[] args)
    {
        // java ArrayEx04 1 1 => 2

        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);

        System.out.println("합계 : " + (num1 + num2));
    }
}

java Gugudan 1 3을 입력 받아서
구구단을 만들고
조건 : 시작단이 끝단보다 크면 에러 출력 후 종료

public class JavaGugudan {
    public static void main(String[] args)
    {
        int col = Integer.parseInt(args[0]);
        int dan = Integer.parseInt(args[1]);

        if (col < dan) {
            for(int i=col; i<=dan; i++) {
                for(int j=1; j<=9; j++) {
                    System.out.println(i + " x " + j + " = " + i*j);
                }
            }
        }
        else {
            System.out.println("에러");
        }
    }
}

강사님이 짠거

public class GugudanEx01 {
    public static void main(String[] args)
    {
        int startDan = Integer.parseInt(args[0]);
        int endDan = Integer.parseInt(args[1]);

        if(startDan >= endDan) {
            System.out.println("시작단이 끝단보다 큽니다.");
        }
        else {
            for(int i=startDan; i<=endDan; i++) {
                for (int j=1; j<=9; j++) {
                    System.out.printf("%2d X %2d = %2d\t", i, j, j*j);
                }
                System.out.println();
            }
        }
    }
}

다차원 배열
2차원 배열의 선언과 인덱스
2차원 배열을 선언하는 방법은 1차원 배열과 같다. 다만 괄호 [ ]가 하나 더 들어갈 뿐이다.

public class ArrayEx05 {
    public static void main(String[] args)
    {
        // 2차원 (행, 열) = 테이블
        int[][] arr1;
        arr1 = new int[3][2];

        arr1[0][0] = 10;
        arr1[0][1] = 20;
        arr1[1][0] = 30;
        arr1[1][1] = 40;
        arr1[2][0] = 50;
        arr1[2][1] = 60;

        // 데이터의 갯수 ; 6
        System.out.println(arr1.length);
        System.out.println(arr1[0].length);
        System.out.println(arr1[2].length);

        // 2중 for statement
        for(int i=0; i<arr1.length; i++) {
            for(int j=0; j<arr1[i].length; j++) {
                System.out.println(arr1[i][j]);
            }
        }
        // 향상된 for
        // 1차원 배열 : 1차원 배열
        for(int[] datas : arr1) {
            for(int data : datas) {
                System.out.println(data);
            }
        }
    }
}

ArrayEx06 : 다차원 배열 선언 / 생성 / 초기화 방법

public class ArrayEx06 {
    public static void main(String[] args)
    {
        int[][] arr1 = new int[][] {{10, 20}, {30, 40}, {40, 50}};
        int[][] arr2 = {{10, 20}, {30, 40}, {40, 50}};
    }
}

ArrayEx19 : 5명의 세 과목 점수 합계 및 평균

public class ArrayEx19 {
    public static void main(String[] args)
    {
        int[][] score = {
                            { 100, 100, 100}
                            , { 20, 20, 20}
                            , { 30, 30, 30}
                            , { 40, 40, 40}
                            , { 50, 50, 50}
        };

        int korTotal = 0, engTotal = 0, mathTotal = 0;

        System.out.println("번호 국어 영어 수학 총점 평균 ");
        System.out.println("============================");

        for(int i=0; i< score.length; i++) {
            int sum = 0;
            float avg = 0.0f;

            korTotal += score[i][0];
            engTotal += score[i][1];
            mathTotal += score[i][2];
            System.out.printf("%3d", i+1);

            for(int j=0; j<score[i].length; j++) {
                sum += score[i][j];
                System.out.printf("%5d", score[i][j]);
            }

            avg = sum/ (float)score[i].length;
            System.out.printf("%5d %5.1f%n", sum, avg);
        }

        System.out.println("============================");
        System.out.printf("총점:%3d %4d %4d%n", korTotal, engTotal, mathTotal);
    }
}

가변 배열
자바에서는 2차원 이상의 배열을 '배열의 배열'의 형태로 처리한다는 사실을 이용하면 보다 자유로운 형태의 배열을 구성할 수 있다.

public class ArrayEx06 {
    public static void main(String[] args)
    {
        int[][] arr1 = new int[][] {{10, 20}, {30, 40}, {40, 50}};
        int[][] arr2 = {{10, 20}, {30, 40}, {40, 50}};

        // 가변 배열
        int[][] arr3 = new int[3][];
        arr3[0] = new int[3];
        arr3[1] = new int[2];
        arr3[2] = new int[1];

        arr3[0][0] = 10;
        arr3[0][1] = 20;
        arr3[0][2] = 30;
        arr3[1][0] = 40;
        arr3[1][1] = 50;
        arr3[2][0] = 60;

        // 향상된 for문을 통해서 출력
        for(int[] datas : arr3) {
            for(int data : datas) {
                System.out.println(data);
            }
        }
    }
}

객체지향언어

프로그램 기법
1. 절차적 프로그래밍
    위 -> 아래로 ...
    => 구조적 프로그래밍(함수 중심 프로그램 : C언어)
=> 합리와 분업(서양)

2. 객체지향 프로그래밍
    OOP (Object Oriented(중심) Programming)
    객체
        - 실세계 사물에서 공통 관점을 추출
        - 실세계 사물에 새로운 자료형 선언(개발자 중심)
            사물
            아반떼
            그랜져    => 추출(공통정의 => 객체(자동차) => 클래스 => 변수(인스턴스)
            소나타
        객체의 구성요소 - 속성과 기능
        속성(property) : 멤버변수, 특성, 필드, 상태
        기능(function) : 메서드, 함수, 행위

    클래스
    * 원래는 클래스당 1개 파일

    *  1개 파일
        - 자료 클래스 : 자료형 => 객체변수(인스턴스)
        - 실행 클래스 : public / 클래스명 = 파일명
            public static void main(String[] args) : 메인 메서드를 포함하고 있는 것

기존에 만들었던 파일과는 다르게 자료 클래스, 실행 클래스 총 2개의 클래스파일이 생성되었다.

TvMain

// 자료 클래스
class Tv {
    // 속성 : 멤버변수 / 필드
    String color;
    boolean power;
    int channel;
}
// 실행 클래스
public class TvMain {
    public static void main(String[] args) {
        // 선언
        Tv tv1;            
        // 생성

        // new : 메모리 생성 연산자
        tv1 = new Tv();         
        // 초기화
        // . 객체 참조 연산자
        tv1.color = "red";      
        tv1.power = true;       
        tv1.channel = 10;      

        System.out.println(tv1.color);
        System.out.println(tv1.power);
        System.out.println(tv1.channel);
        // tv의 주소
        System.out.println(tv1);
    }
}

tv1 의 주소

// 자료 클래스
class Tv {
    // 속성 : 멤버변수 / 필드
    String color;
    boolean power;
    int channel;
}
// 실행 클래스
public class TvMain {
    public static void main(String[] args) {
        // 선언
        Tv tv1;            
        // 생성

        // new : 메모리 생성 연산자
        tv1 = new Tv();         
        // 초기화
        // . 객체 참조 연산자
        tv1.color = "red";      
        tv1.power = true;       
        tv1.channel = 10;      

        System.out.println(tv1.color);
        System.out.println(tv1.power);
        System.out.println(tv1.channel);
        // tv의 주소
        System.out.println(tv1);

        Tv tv2 = new Tv();
        System.out.println(tv2);
    }
}

tv 2의 주소

// 자료 클래스
class Tv {
    // 속성 : 멤버변수 / 필드
    String color;
    boolean power;
    int channel;
}
// 실행 클래스
public class TvMain {
    public static void main(String[] args) {
        // 선언
        Tv tv1;            
        // 생성

        // new : 메모리 생성 연산자
        tv1 = new Tv();         
        // 초기화
        // . 객체 참조 연산자
        tv1.color = "red";      
        tv1.power = true;       
        tv1.channel = 10;      

        System.out.println(tv1.color);
        System.out.println(tv1.power);
        System.out.println(tv1.channel);
        // tv의 주소
        System.out.println(tv1);

        Tv tv2 = new Tv();
        System.out.println(tv2);
        // 주소를 할당
        Tv tv3 = tv1;
        System.out.println(tv3);
        System.out.println(tv3.color);
        System.out.println(tv3.channel);

        int a = 10;
        // 값을 할당
        int b = a;
    }
}

TvTest3

class Tv {
    String color;
    boolean power;
    int channel;

    void power() {
        power = !power;
    }
    void channelUp() {
        ++channel;
    }
    void channelDown() {
        --channel;
    }
}

public class TvTest3 {
    public static void main(String[] args)
    {
        Tv t1 = new Tv();
        Tv t2 = new Tv();
        System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
        System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
        t2 = t1;
        t1.channel = 7;
        System.out.println("t1의 channel값을 7로 변경하였습니다.");
        System.out.println("t1의 channel값은 " + t1.channel + "입니다.");
        System.out.println("t2의 channel값은 " + t2.channel + "입니다.");
    }
}

메서드
: 특정 작업을 수행하는 일련의 문장들을 하나로 묶은 것이다. '변수와 제어문으로 묶는 것'이다.
메서드를 사용하는 이유
1. 높은 재사용성
2. 중복된 코드의 제거
3. 프로그램의 구조화

메서드의 선언과 구현

class Method {
    // 메서드 선언
    void doTest1() {
        // 지역변수
        // 제어문
        System.out.println("doTest1() 호출");
    }
}

public class MethodEx01 {
    public static void main(String[] args)
    {
        Method m = new Method();
        // 메서드 호출
        m.doTest1();
    }
}

메서드 안에 지역변수는 초기화를 해주지 않으면 에러난다.

해당 메서드 안에서만 지역변수 값이 적용된다.

데이터를 받아 메서드에 입력하고 싶을 때

class Method {
    // 메서드 선언
    void doTest1() {
        // 지역변수
        // 제어문
        int data1 = 10;
        System.out.println("doTest1() 호출 : " + data1);
    }

    void doTest2(int data1, int data2) {
        System.out.println("doTest1() 호출 : " + data1);
        System.out.println("doTest2() 호출 : " + data2);
    }
}

public class MethodEx01 {
    public static void main(String[] args)
    {
        Method m = new Method();
        // 메서드 호출
        m.doTest1();
        m.doTest2(10, 20);
    }
}

Return을 사용할 시

class Method {
    // 메서드 선언
    void doTest1() {
        // 지역변수
        // 제어문
        int data1 = 10;
        System.out.println("doTest1() 호출 : " + data1);
    }

    void doTest2(int data1, int data2) {
        System.out.println("doTest1() 호출 : " + data1);
        System.out.println("doTest2() 호출 : " + data2);
    }
    // void - return (x) 그 외 return이 있는 것은 return의 자료형을 써준다
    int doTest3(int data1, int data2) {
        int sum = data1 + data2;
        return sum;
    }
}

public class MethodEx01 {
    public static void main(String[] args)
    {
        Method m = new Method();
        // 메서드 호출
        m.doTest1();
        m.doTest2(10, 20);

        int r = m.doTest3(10, 20);
        System.out.println(r);
    }
}

오버로딩
매서드도 변수와 마찬가지로 같은 클래스 내에서 서로 구별될 수 있어야 하기 때문에 각기 다른 이름을 가져야 한다. 그러나 자바에서는 한 클래스 내에 이미 사용하려는 이름과 같은 이름을 가진 매서드가 있더라도 매개변수의 개수 또는 타입이 다르면, 같은 이름을 사용해서 메서드를 정의할 수 있다.
이처럼, 한 클래스 내에 같은 이름의 메서드를 여러 개 정의하는 것을 '메서드 오버로딩' 또는 간단히 오버로딩이라고 한다.

오버로딩(중복정의)의 조건
1. 메서드 이름이 같아야 한다.
2. 매개변수의 개수 또는 타입이 달라야 한다.

MethodEx02 오버로딩

class Method {
    void doTest() {
        System.out.println("doTest() 호출");
    }

    void doTest() {
        System.out.println("doTest() 호출");
    }
}

public class MethodEx02 {
    public static void main(String[] args)
    {
        
    }
}

에러 발생

class Method {
    void doTest(int a) {
        System.out.println("doTest() 호출");
    }

    void doTest(String s) {
        System.out.println("doTest() 호출");
    }
}

public class MethodEx02 {
    public static void main(String[] args)
    {
        
    }
}

오버 로딩

class Method {
    void doTest(int a) {
        System.out.println("doTest() 호출");
    }
    // 자료형
    void doTest(String s) {
        System.out.println("doTest() 호출");
    }
    // 갯수
    void doTest(String s, int a) {
        System.out.println("doTest() 호출");
    }
}

public class MethodEx02 {
    public static void main(String[] args)
    {
        
    }
}

갯수가 달라져도 오버로딩 가능

class Method {
    void doTest(int a) {
        System.out.println("doTest() 호출");
    }
    // 자료형
    void doTest(String s) {
        System.out.println("doTest() 호출");
    }
    // 갯수
    void doTest(String s, int a) {
        System.out.println("doTest() 호출");
    }

    void doTest(int a, String s) {
        System.out.println("doTest() 호출");
    }
}

public class MethodEx02 {
    public static void main(String[] args)
    {
        
    }
}

갯수 순서가 달라져도 오버로딩 가능

class Method {
    void doTest(int a) {
        System.out.println("doTest() 호출");
    }
    // 자료형
    void doTest(String s) {
        System.out.println("doTest() 호출");
    }
    // 갯수
    void doTest(String s, int a) {
        System.out.println("doTest() 호출");
    }

    void doTest(int a, String s) {
        System.out.println("doTest() 호출");
    }

    int doTest(int a, String s) {
        System.out.println("doTest() 호출");
        return 10;
    }
}

public class MethodEx02 {
    public static void main(String[] args)
    {
        
    }
}

return 10; 이 들어갔지만 오버로딩이 되는 조건으로 보긴 어렵다

class Method {
    void doTest(int a) {
        System.out.println("doTest() 호출");
    }
    // 자료형
    void doTest(String s) {
        System.out.println("doTest() 호출");
    }
    // 갯수
    void doTest(String s, int a) {
        System.out.println("doTest() 호출");
    }

    void doTest(int a, String s) {
        System.out.println("doTest() 호출");
    }

    int doTest(int a, String s, int b) {
        System.out.println("doTest() 호출");
        return 10;
    }
}

public class MethodEx02 {
    public static void main(String[] args)
    {
        
    }
}

int b가 추가되어 오버로딩 조건이 충족되었다

 

 

반응형

댓글