Java

자바의 정석 [Ch.06] 2

eunjineee 2024. 1. 24. 08:11

배열

  • 동일한 데이터 타입을 순차적으로
  • 레퍼런스 방식으로 잡히고 > 메모리는 힙에 있음 (레퍼런스)

레퍼런스 타입

힙 > 동적 메모리 할당

int [] arr;             ----> 레퍼런스만 있는 상태
arr = new id[4];        ----> 객체 지정

타입 일차원배열 

int [][] arr;

항상 접근하는 포인터 기준으로 0번이 결정되는 것

Length

length

public class ArrayExam {
    public static void main(String[] args) {
        int []arr;
        arr = new int[4];

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


    //for each문
        for(int j:arr) {
            System.out.println(j);
        }

        int[][] arr2;
        arr2 = new int[2][];
        arr2[0] = new int [3];
        arr2[1] = new int [5];

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

        str[0] = new String("A");
        str[1] = new String("B");
        str[2] = new String("C");

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

예제

import java.util.Scanner;

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


        // 1 사람 성적
        // 입력 : 이름 국 영 수
        // 연산 : 총점 평균
        // 출력 : 이름 국 영 수 총 평

        String name;
        int[]score = new int [4];
        float avg;

        Scanner sc = new Scanner(System.in);
        System.out.println("이름을 입력하세요.");
        name = sc.next();
        System.out.println("국, 영, 수 점수를 입력하세요");
        for(int i=0; i< score.length-1; i++) {
            score[i] = sc.nextInt();
            score[3] += score[i];
        }

        avg = score[3] / (float) (score.length-1);

        System.out.println(name+"님의 국어, 영어, 수학, 총점, 평균입니다.");

        for(int j: score) {
            System.out.print(j+" ");
        }
        System.out.print(avg);

        // 3 사람 성적
        // 입력 : 이름 국 영 수
        // 연산 : 총점 평균
        // 출력 : 이름 국 영 수 총 평

        String [] name = new String [3];
        int [][] score = new int [3][4];
        float [] avg = new float [3];
        Scanner sc = new Scanner(System.in);

        for(int p=0; p<3; p++) {

            System.out.println("이름을 입력하세요.");
            name[p] = sc.next();

            System.out.println("국, 영, 수 점수를 입력하세요");

            for(int i=0; i< score[p].length-1; i++) {
                score[p][i] = sc.nextInt();
                score[p][3] += score[p][i];
            }

            avg[p] = score[p][3] / (float) (score[p].length-1);
        }


        for(int n=0; n<3; n++) {
            System.out.println(name[n]+"님의 국어, 영어, 수학, 총점, 평균입니다.");

            for(int j: score[n]) {
                System.out.print(j+" ");
            }
            System.out.print(avg[n]);
            System.out.println();
        }


        // 사람수 사람 성적
        // 입력 : 이름 국 영 수
        // 연산 : 총점 평균
        // 출력 : 이름 국 영 수 총 평
        Scanner sc = new Scanner(System.in);        

        System.out.println("몇 명인지 사람 수를 입력해주세요.");
        int per = sc.nextInt();

        String [] name = new String [per];
        int [][] score = new int [per][4];
        float [] avg = new float [per];



        for(int p=0; p<per; p++) {

            System.out.println("이름을 입력하세요.");
            name[p] = sc.next();

            System.out.println("국, 영, 수 점수를 입력하세요");

            for(int i=0; i< score[p].length-1; i++) {
                score[p][i] = sc.nextInt();
                score[p][3] += score[p][i];
            }

            avg[p] = score[p][3] / (float) (score[p].length-1);
        }


        for(int n=0; n<per; n++) {
            System.out.println(name[n]+"님의 국어, 영어, 수학, 총점, 평균입니다.");

            for(int j: score[n]) {
                System.out.print(j+" ");
            }
            System.out.print(avg[n]);
            System.out.println();
        }

    }
}

Method

  • 데이터를 외부에서 사용할 수 있게 해주는 기능
  1. static method
    • 객체를 생성하지 않고 사용이 가능하다.
    • class이름.method명() 호출 [직관적인 사용가능]
    • this 레퍼런스를 가지고 있지는 않다.
  2. instance method
    • 객체를 생성한 후에 사용이 가능하다.
    • this 레퍼런스를 가지고 있다.
    • 리턴타입 함수명(매개변수){ 리턴 타입은 무조건 한개만 올 수 있음 }
  3. 메소드들은 주로 접근지정자를 public으로 지정
  4. 모듈화
    1. call by name
    2. call by value
    3. call by reference

**void 무치화

Class 구성요소

  1. Constructor (생성자함수)
    • 객체등록, 객체생성시 자동호출
    • 개발자는 객체생성시 필드를 초기화하는 목적
    • 디폴트 생성자 제공 → 명시적으로 생성자를 만들지 않을 경우
    • 오버로딩이 가능하다.
    • 주로 public 지정( 객체는 외부에서 더 많이 쓰기 때문에 )( static으로 연결 가능)
    • 리턴타입이 없다.
    • 클래스 명과 동일한 이름.
  2. field
    • 객체를 사용할 때 지속적으로 사용되어지는 데이터를 필드로 지정
    • 주로 private로 지정
    • [범용적으로 쓰는 부분만]
  3. method
    • 오버로딩이 가능
    • 주로 public으로 지정
    • 외부에서 내부의 필드를 접근하기 위해 제공.
    • setter, getter 를 제공하는 것을 추천.
    • setKor(), getKor()
    • this instance method의 첫번째 매개변수 위치에 항상 존재한다.

오버로딩

**동일한 기능을 하는 것끼리 오버로딩으로 사용.

  1. 함수명은 동일해야한다.
  2. 매개변수의 타입 또는 갯수에 의해서 구별이 가능해야한다.
  3. 리턴타입은 상관하지 않음

this

  1. 인스턴스 메소드의 첫번째 매개변수로 항상 존재
  2. 자기자신을 접근하는 레퍼런스 변수
  3. 선언할 수 없고 사용만 가능함
  • 전역변수 잡는 this
public class ClassExam {

    //field
    private int a;

    public ClassExam() {                        //ClassExam this
        System.out.println("생성자 호출"+a);
    }    

    public ClassExam(int aa) {                  //ClassExam this, aa
        a = aa;
        System.out.println("생성자 호출"+a);
    }

    public void setA(int a) {                 //ClassExam this, aa
        a = a;         //지역변수a = 지역변수a > 필드랑 지역변수 변수명 같으면 지역변수로 인식해서
                                            //setA가 받은 매개변수 a로 인식함 매개a=매개a가 되는 현상
    }

//    public void setA(int a) {                 //ClassExam this, aa
//        this.a = a;         //필드 a[전역변수]를 잡아줌
//    }

    public int getA() {                        //ClassExam this
        return a;
    }

    public ClassExam getObject() {
        return this;  //자기자신을 리턴할 때 사용
    }
    public static void main(String [] args){
        ClassExam ce = new ClassExam();
//        ClassExam ce1 = new ClassExam(100);

        ce.setA(100);   //ce, 100
        System.out.println(ce.getA());
    }
}

this()

생성자에서 또 다른 생성자를 호출할 때 사용한다.

관리차원에서 좀 더 수월하다.

**함수는 호출되지 않는 이상 메모리를 차지하지 않는다

계산기

import java.util.Scanner;

public class Calculator {

    private int a;
    private int b;
    private int ans;


    public Calculator(int a, char str, int b) {     //입력만 있고 연산 기능은 없다, 계산 기능은 따로 빼는 것이 좋다
        this.a = a;
        this.b = b;


        switch(str) {
        case '+': this.ans = this.a + this.b; break;
        case '-': this.ans = this.a - this.b; break;
        case '/': this.ans = this.a / this.b; break;
        case '*': this.ans = this.a * this.b; break;
        default : System.out.println("수식을 다시 입력하세요");
        }
    }

    public void setA(int a) {
        this.a = a;
    }
    public void setB(int b) {
        this.b = b;
    }

    public int getAns() {
        return ans;
    }


    public static void main(String[] agrs) {
        Scanner sc = new Scanner(System.in);
        Character k;

        do {
            System.out.print("식을 입력하세요 : ");

            Calculator cal1 = new Calculator(sc.nextInt(),sc.next().charAt(0),sc.nextInt());
            System.out.println(cal1.getAns());

            System.out.print("계속하시겠습니까? (Y/N)");
            k = sc.next().charAt(0);
        }while(k == 'Y'||k == 'y');
    }
}