minghxx.blog
  • 자바의 정석 연습문제 ch 6 객체지향 프로그래밍(1)
    2023년 08월 31일 11시 49분 54초에 업로드 된 글입니다.
    작성자: 민발자
    728x90

    자바의 정석 3판 기초판 연습문제

    https://github.com/castello/javajungsuk3

     

    GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition

    soure codes and ppt files of javajungsuk 3rd edition - GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition

    github.com

     

    [6-1] 다음과 같은 멤버변수를 갖는 SutdaCard클래스를 정의하시오.

    타입 변수명 설명
    int num 카드의 숫자(1~10사이의 정수)
    boolean isKwang 광이면 true, 아니면 false
    class sutdaCard {
    	int num;
    	boolean isKwang;
    }

     

    [6-2] 문제6-1에서 정의한 SutdaCard클래스에 두 개의 생성자와 info()를 추가해서 실행 결과와 같은 결과를 얻도록 하시오.

    public class Ex6_2 {
    	public static void main (String args[]) {
    		SutdaCard card1 = new SutdaCard(3, false);
    		SutdaCard card2 = new SutdaCard();
    		
    		System.out.println(card1.info());
    		System.out.println(card2.info());
    	}
    }
    
    class SutdaCard{
    	// (1)
    }
    int num;
    boolean isKwang;
    
    // 생성자
    SutdaCard() {
        this(1, true);
    }
    
    SutdaCard(int num, boolean isKwang){
        this.num = num;
        this.isKwang = isKwang;
    }
    
    // info메서드
    String info() {
        return num + (isKwang? "K": "");
    
    }

     

    [6-3] 다음과 같은 멤버변수를 갖는 Student클래스를 정의하시오.

    타입 변수명 설명
    String name 학생이름
    int  ban
    int no 번호
    int kor 국어점수
    int eng 영어점수
    int math 수학점수
    class Student {
    	String name;
    	int ban;
    	int no;
    	int kor;
    	int eng;
    	int math;
    }

     

     

    [6-4] 문제6-3에서 정의한 Student클래스에 다음과 같이 정의된 두 개의 메서드 getTotal()과 getAverage()를 추가하시오.

    1. 메서드명 : getTotal

    기능 : 국어, 영어, 수학의 점수를 모두 더해서 반환

    반환타입 : int

    매개변수 : 없음

     

    2. 메서드명 : getAverage

    기능 : 총점(국어+영어+수학)을 과목수로 나눈 평균을 구한다. 소수점 둘째자리에서 반올림할 것

    반환타입 : float

    매개변수 : 없음

    public class Ex6_3 {
    	public static void main(String[] args) {
    		Student s = new Student();
    		s.name = "홍길동";
    		s.ban = 1;
    		s.no = 1;
    		s.kor = 100;
    		s.eng = 60;
    		s.math = 76;
    		
    		System.out.println("이름: " + s.name);
    		System.out.println("총점: " + s.getTotal());
    		System.out.println("평균: " + s.getAverage());
    	}
    }
    
    class Student {
    	String name;
    	int ban;
    	int no;
    	int kor;
    	int eng;
    	int math;
    }
    int getTotal() {
        return kor + eng + math;
    }
    
    float getAverage() {
        return Math.round(getTotal() / 3f * 10) / 10f;
    }

     

    [6-5] 다음과 같은 실행결과를 얻도록 Student클래스에 생성자와 info()를 추가하시오.

    public class Ex6_3 {
    	public static void main(String[] args) {
    		Student s = new Student("홍길동", 1, 1, 100, 60 , 76);
    		
    		System.out.println(s.info());
    	}
    }
    
    class Student {
    	String name;
    	int ban;
    	int no;
    	int kor;
    	int eng;
    	int math;
    	
    	Student(String name, int ban, int no, int kor, int eng, int math) {
    		this.name = name;
    		this.ban = ban;
    		this.no = no;
    		this.kor = kor;
    		this.eng = eng;
    		this.math = math;
    	}
    	
    	int getTotal() {
    		return kor + eng + math;
    	}
    	
    	float getAverage() {
    		return Math.round(getTotal() / 3f * 10) / 10f;
    	}
    	
    	String info() {
    		return name + "," + ban + "," + no + "," +kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage();
    	}
    }

     

    [6-6] 두 점의 거리를 계산하는 getDistance()를 완성하시오.

    [Hint] 제곱근 계산은 Math.sqrt(double a)를 사용하면 된다.

    // 두점 (x, y)와 (x1, y1)간의 거리를 구한다.
    static double getDistance(int x, int y, int x1, int y1) {
        return // (1)
    }
    
    public static void main(String[] args) {
        System.out.println(getDistance(1, 1, 2, 2));
    }
    Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));

     

    [6-7] 문제6-6에서 작성한 클래스메서드 getDistance()를 MyPoint클래스의 인스턴스메서 드로 정의하시오.

    class MyPoint {
    	int x;
    	int y;
    	
    	MyPoint(int x, int y) {
    		this.x = x;
    		this.y = y;
    	}
    	
    	// (1)
    }
    
    public class Ex6_7 {
    	
    	public static void main(String[] args) {
    		MyPoint p = new MyPoint(1, 1);
    		
    		// p와 (2, 2)의 거리를 구한다.
    		System.out.println(p.getDistance(2,2));
    	}
    
    }
    double getDistance(int x1, int y1){
        return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
    }

     

    [6-8] 다음의 코드에 정의된 변수들을 종류별로 구분해서 적으시오.

    class PlayingCard{
    	int kind;
    	int num;
    	
    	static int width;
    	static int height;
    	
    	PlayingCard(int k, int n) {
    		kind = k;
    		num = n;
    	}
    }
    
    public class Ex6_8 {
    
    	public static void main(String[] args) {
    		PlayingCard card = new PlayingCard(1, 1);
    	}
    
    }

    클래스 변수 : width, height

    인스턴스 변수 : kind, num

    지역 변수 : k, n, card, args

     

    [6-9] 다음은 컴퓨터 게임의 병사(marine)를 클래스로 정의한 것이다. 이 클래스의 멤버 중에 static을 붙여야 하는 것은 어떤 것들이고 그 이유는 무엇인가?
    (단, 모든 병사의 공격력과 방어력은 같아야 한다.)

    class Marine {
    	int x = 0, y = 0; // 위치좌표
    	int hp = 60; // 체력
    	static int weapon = 6; // 공격력
    	static int armor = 0; // 방어력 
    	
    	static void weaponUp() {
    		weapon++;
    	}
    	
    	static void armorUp() {
    		armor++;
    	}
    	
    	void move(int x, int y) {
    		this.x = x;
    		this.y = y;
    	}
    }

    공격력과 방어력이 모두 같으므로 static, static 변수를 사용하는 메서드도 static

     

    [6-10] 다음 중 생성자에 대한 설명으로 옳지 않은 것은? (모두 고르시오)

    a. 모든 생성자의 이름은 클래스 이름과 동일해야한다.

    b. 생성자는 객체를 생성하기 위한 것이다.

    c. 클래스에는 생성자가 반드시 하나 이상 있어야 한다. 

    d. 생성자가 없는 클래스는 컴파일러가 기본 생성자를 추가한다. 

    e. 생성자는 오버로딩 할 수 없다.

     

    → 객체를 초기화하는 목적, 생성은 new 연산자

    → 오버로딩 가능, 하나의 클래스에 여러 생성자 정의 가능

     

    [6-11] 다음 중 this에 대한 설명으로 맞지 않은 것은? (모두 고르시오)

    a. 객체 자신을 가리키는 참조변수이다.

    b. 클래스 내에서라면 어디서든 사용할 수 있다.

    c. 지역변수와 인스턴스변수를 구별할 때 사용

    d. 클래스 메서드 내에서는 사용할 수 없다. 

     

    → 클래스 멤버에서는 사용 불가, this는 인스턴스 자신의 주소 저장, 인스턴스 메서드에 존재하는 지역변수, 인스턴스 메서드 내에서만 사용

     

    [6-12] 다음 중 오버로딩이 성립하기 위한 조건이 아닌 것은? (모두 고르시오)

    a. 메서드의 이름이 같아야 한다.

    b. 매개변수의 개수나 타입이 달라야 한다.

    c. 리턴 타입이 달라야 한다.

    d. 매개변수의 이름이 달라야 한다. 

     

    [6-13] 다음 중 아래의 add메서드를 올바르게 오버로딩 한 것은? (모두 고르시오)

    long add(int a, int b) {
    	return a+b;
    }

    a. long add(int x, int y) { return x+y; }

    b. long add(int a, int b) { return a+b; }

    c. int add(byte a, byte b) { return a+b; }

    d. int add(long a, long b) { return (int)(a+b); }

     

    오버로딩 조건

    메서드 이름이 같고, 매개변수 개수 또는 타입이 달라야한다. 매개변수는 같고 리턴타입이 다른 경우 성립되지 않는다.

     

    [6-14] 다음 중 초기화에 대한 설명으로 옳지 않은 것은? (모두 고르시오)

    a. 멤버 변수는 자동 초기화되므로 초기화하지 않고도 값을 참조할 수 있다.

    b. 지역 변수는 사용하기 전에 반드시 초기화해야 한다.

    c. 초기화 블럭보다 생성자가 먼저 수행된다.

    d. 명시적 초기화를 제일 우선적으로 고려해야 한다.

    e. 클래스 변수보다 인스턴스 변수가 먼저 초기화된다.

     

     초기화 블럭이 먼저 수행

     클래스 변수가 먼저 초기화

    클래스 변수는 클래스가 처음 메모리에 로딩시 자동 초기화, 생성자는 초기화 블럭이 수행된 다음에 수행

     

    [6-15] 다음중 인스턴스변수의 초기화 순서가 올바른 것은?

    a. 기본값  명시적 초기화  초기화 블럭  생성자

    b. 기본값  명시적 초기화  생성자 초기화 블럭

    c. 기본값 초기화 블럭  명시적 초기화  생성자

    d. 기본값  초기화 블럭  생성자 명시적 초기화

     

    변수의 초기화 시점

    클래스 변수의 초기화 : 클래스 처음 로딩시 단 한번 초기화

    인스턴스 변수의 초기화 : 인스턴스 생성될 때마다 각 인스턴스별로 초기화

    클래스 변수 초기화 : 기본값  명시적 초기화  클래스 초기화 블럭

    인스턴스 변수의 초기화 순서 : 기본값  명시적 초기화  인스턴스 초기화 블럭 생성자

     

    [6-16] 다음 중 지역변수에 대한 설명으로 옳지 않은 것은? (모두 고르시오)

    a. 자동 초기화되므로 별도의 초기화가 필요없다.

    b. 지역 변수가 선언된 메서드가 종료되면 지역변수도 함께 소멸

    c. 매서드의 매개변수로 선언된 변수도 지역변수이다.

    d. 힙 영역에 생성되며 가비지 컬렉터에 의해 소멸

    e. 클래스 변수나 인스턴스 변수보다 메모이 부담이 적다.

     

    지역변수는 자동 초기화 되지 않음, 선언된 블럭이나 매서드가 종료되면 소멸되므로 메모리 부담이 적음, 힙영역은 인스턴스변수가 생성되는 영역, 지역변수는 호출 스택에 생성

     

    [6-17] 호출스택이 다음과 같은 상황일 때 옳지 않은 설명은? (모두 고르시오)

    a. 제일 먼저 호출 스택에 저장된 것은 main 메서드 

    b. println 메서드를 제외한 나머지 메서드들은 모두 종료된 상태

    c. method2 메서드를 호출한 것은 main메서드이다. 

    d. println메서드가 종료되면 method1메서드가 수행을 재개한다.

    e. main-metho2-method1-println의 순서로 호출  

    f. 현재 실행중인 메서드는 prinfln 뿐이다.

     

    호출 스택 안에 있는 나머지 메서드들은 대기 상태, 맨 위 메서드가 현재 실행중인 메서드

     

    [6-18] 다음의 코드를 컴파일하면 에러가 발생한다. 컴파일 에러가 발생하는 라인과 그 이유를 설명하시오.

    class MemberCall{
    	int iv = 0;
    	static int cv = 20;
    	
    	int iv2 = cv;
    	static int cv2 = iv; // 라인A
    	
    	static void staticMethod1(){
    		System.out.println(cv);
    		System.out.println(iv); // 라인B
    	}
    	
    	void instanceMethod1() {
    		System.out.println(cv);
    		System.out.println(iv); // 라인C
    	}
    	
    	static void staticMethod2(){
    		staticMethod1();
    		instanceMethod1(); // 라인D
    	}
    	
    	void instanceMethod2() {
    		staticMethod1(); // 라인E
    		instanceMethod1();
    	}
    	
    	
    }

    A, B, D

    A static 변수 초기화에 인스턴스 변수 사용 불가, 사용하려면 객체 생성 후 사용 가능

    B static 메서드에는 인스턴스 변수 사용 불가 

    D static 메서드에서는 인스턴스 메서드 사용 불가

     

    [6-19] 다음 코드의 실행 결과를 예측하여 적으시오.

    public class Ex6_19 {
    	public static void chang(String str) {
    		str +="456";
    	}
    	
    	public static void main(String[] args) {
    		String str = "ABC123";
    		System.out.println(str);
    		chang(str);
    		System.out.println("After change: " + str);
    	}
    }

    문자열은 내용을 변경할 수 없기 때문에 덧셈 연산으로 인해 메서드 str과 main의 str은 서로 다른 변수가 됨

    change메서드가 종료되면 사용하던 메모리를 반환하므로 ABC123456인 문자열은 제거되어 마지막에 출력되는 str은 ABC123

     

     

    [6-20] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.

    [주의] Math.random()을 사용하는 경우 실행결과와 다를 수 있음.

    메서드명 : shuffle

    기능 : 주어진 배열에 담긴 값의 위치를 바꾸는 작업을 반복하여 뒤섞이고 처리한 배열을 반환

    반환 타입 : int[]

    매개변수 : int[] arr - 정수값이 담긴 배열

    public class Ex6_20 {
    	
    	// (1)
    	
    	public static void main(String[] args) {
    		int[] original = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    		System.out.println(Arrays.toString(original));
    		
    		int[] result = shuffle(original);
    		System.out.println(Arrays.toString(original));
    	}
    
    }
    static int[] shuffle(int[] arr) {
        for(int i = 0; i < arr.length; i++) {
            int idx = (int)Math.random() * arr.length;
    
            int tmp = arr[i];
            arr[i] = arr[idx];
            arr[idx] = tmp;
        }
        return arr;
    }

     

    [6-21] Tv클래스를 주어진 로직대로 완성하시오. 완성한 후에 실행해서 주어진 실행결과와 일치하는지 확인하라.

    class MyTv {
    	boolean isPowerOn;
    	int channel;
    	int volume;
    	
    	final int MAX_VOLUME = 100;
    	final int MIN_VOLUME = 10;
    	final int MAX_CHANNEL = 100;
    	final int MIN_CHANNEL = 1;
    	
    	void turnOff() {
    		// 1) isPowerOn의 값이 true면 false로 false면 true로 변경
    	}
    	
    	void volumeUp() {
    		// 2) volume의 값이 MAX_VOLUME보다 작을 때만 값 1 증가
    	}
    	
    	void volumeDown() {
    		// 3) volume의 값이 MIN_VOLUME보다 클 때만 값 1 감소
    	}
    	
    	void channelUp() {
    		// 4) channel의 값 1 증가 MAX_CHANNEL이면 MIN_CHANNEL로 변경
    	}
    	
    	void channelDown() {
    		// 5) channel의 값 1 감소 MIN_CHANNEL이면 MAX_CHANNEL로 변경
    	}
    }
    
    public class Ex6_21 {
    	
    	public static void main(String[] args) {
    		MyTv t = new MyTv();
    		t.channel = 100;
    		t.volume = 0;
    		System.out.println("CH: " + t.channel + ", VOL: " + t.volume);
    		
    		t.channelDown();
    		t.volumeDown();
    		System.out.println("CH: " + t.channel + ", VOL: " + t.volume);
    		
    		t.volume = 100;
    		t.channelUp();
    		t.volumeUp();
    		System.out.println("CH: " + t.channel + ", VOL: " + t.volume);
    	}
    }
    void turnOff() {
        // 1) isPowerOn의 값이 true면 false로 false면 true로 변경 
        isPowerOn = !isPowerOn;
    }
    
    void volumeUp() {
        // 2) volume의 값이 MAX_VOLUME보다 작을 때만 값 1 증가
        if(volume < MAX_VOLUME)
            volume++;
    }
    
    void volumeDown() {
        // 3) volume의 값이 MIN_VOLUME보다 클 때만 값 1 감소
        if(volume > MIN_VOLUME)
            volume--;
    }
    
    void channelUp() {
        // 4) channel의 값 1 증가 MAX_CHANNEL이면 MIN_CHANNEL로 변경
        if(channel == MAX_CHANNEL) {
            channel = MIN_CHANNEL;
        } else {
            channel++;
        }
    }
    
    void channelDown() {
        // 5) channel의 값 1 감소 MIN_CHANNEL이면 MAX_CHANNEL로 변경
        if(channel == MIN_CHANNEL) {
            channel = MAX_CHANNEL;
        } else {
            channel--;
        }
    }

      

    [6-22] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.

    메서드명 : isNumber

    기능 : 주어진 문자열이 모두 숫자로만 이루어져있는지 확인, 모두 숫자로 이루어져 있으면 true, 그렇지 않으면 false 반환, 만일 주어진 문자열이 null이거나 빈문자열"" 이라면 false 반환

    반환타입 : boolean

    매개변수 : String str - 검사할 문자열

    public class Ex6_22 {
    	// (1)
        
    	public static void main(String[] args) {
    		String str = "123";
    		System.out.println(str + "는 숫자입니까?" + isNumber(str));
    		
    		str = "1234o";
    		System.out.println(str + "는 숫자입니까?" + isNumber(str));
    	}
    }
    public static boolean isNumber(String str) {
        if(str == null || str.equals("")) {
            return false;
        }
        for(int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if(ch < '0' || ch > '9') {
                return false;
            }
        }
        return true;
    }

     

    [6-23] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.

    메서드명 : max

    기능 : 주어진 int형 배열의 값 중에서 제일 큰 값을 반환, 만일 주어진 배열이 null이거나 크기가 0인 경우 -999999를 반환한다.

    반환타입 : int

    매개변수 : int[] arr -최대값을 구할 배열

    public static int max(int[] arr) {
    	// (1)
    }
    public static void main(String[] args) {
        int[] data = {3, 2, 9, 4, 7};
        System.out.println(Arrays.toString(data));
        System.out.println("최대값: " + max(data));
        System.out.println("최대값: " + max(null));
        System.out.println("최대값: " + max(new int[]{}));
    }
    public static int max(int[] arr) {
        if(arr == null || arr.length == 0) {
            return -999999;
        }
        int max = 0;
        for(int i = 0; i < arr.length; i++) {
            if(max < arr[i]) {
                max = arr[i];
            }
        }
        return max;
    }

     

    [6-24] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.

    메서드명 : abs

    기능 : 주어진 값의 절대값을 반환

    반환타입 : int 

    매개변수 : int value

    public static int abs(int value) {
        // (1)
    }
    public static void main(String[] args) {
        int value = 5;
        System.out.println(value + "의 절대값: " + abs(value));
        value = -10;
        System.out.println(value + "의 절대값: " + abs(value));
    }
    public static int abs(int value) {
        return value >=0 ? value : -value;
    }
    728x90
    댓글