티스토리 뷰

명품 자바 에센셜 Chapter 4 실습문제.

 

*진도 순서에 맞는 문법으로만 코딩한 것이며, 아직 나오지 않은 문법은 배제하고 풀이하였습니다.


1.아래 실행 결과와 같이  출력하는 다음 main()을 가진 Song 클래스를 작성하라. Song 클래스는 노래 제목 title 필드, 생성자, getTitle() 메소드로 구성된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Song {
    private String songname;
    
    public Song(String songname){
        this.songname = songname;
    }
    
    private String getTitle(){
        return songname;
    }
    public static void main(String[] argv){
        Song mySong = new Song("Let it go");
        Song yourSong = new Song("강남스타일");
        
        System.out.println("내 노래는 " + mySong.getTitle());
        System.out.println("내 노래는 " + yourSong.getTitle());
    }
}
cs

2. 다음은 이름(name 필드)과 전화번호(tel 필드)를 가진 Phone 클래스이다. 이름과 전화번호를 입력받아 2개의 Phone 객체를 생성하고, 출력하는 main() 메소드를 작성하라.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Scanner;
public class Phone {
    private String name, tel;
    
    public Phone(String name, String tel){
        this.name = name;
        this.tel = tel;
    }
    
    public String getName(){return name;}
    public String getTel(){return tel;}
    
    public static void main(String[] argv){
        Scanner sc = new Scanner(System.in);
        
 
        System.out.print("이름과 전화번호 입력>>");
        Phone person1 = new Phone(sc.next(),sc.next());
        System.out.print("이름과 전화번호 입력>>");
        Phone person2 = new Phone(sc.next(),sc.next());
        
        System.out.println(person1.name+ " " +person1.tel);
        System.out.println(person2.name+ " " +person2.tel);
    }
}
cs

3. 사각형을 표현하는 다음 Rect 클래스를 활용하여, Rect 객체 배열을 생성하고, 사용자로부터 4개의 사각형을 입력받아 배열에 저장한 뒤, 배열을 검색하여 사각형 면적의 합을 출력하는 main() 메소드를 가진 RectArray 클래스를 작성하라.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.Scanner;
public class Rect {
    private int width, height;
    public Rect(int width, int height){
        this.width = width;
        this.height = height;
    }
    public int getArea(){return width*height;}
    public static void main(String[] argv){
        Scanner sc = new Scanner(System.in);
        Rect[] r = new Rect[4];
        int sum = 0;
        
        for(int i = 0; i < 4; i++){
            System.out.print((i+1+ " 너비와 높이 >>");
            r[i] = new Rect(sc.nextInt(),sc.nextInt());
            sum += r[i].getArea();
        }
        System.out.println("저장하였습니다..");
        
        System.out.println("사각형의 전체 합은 " + sum);
    }
}
cs


4. 이름과 전화번호 필드, 생성자 및 필요한 메소드를 가진 Phone 클래스를 작성하고, 다음 실행 사례와 같이 작동하도록 main()을 가진 PhoneManager 클래스를 작성하라. 한 사람의 전화번호는 하나의 Phone 객체로 다룬다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Scanner;
class Phone{
    String name;
    String tel;
    Phone(String name, String tel){
        this.name = name;
        this.tel = tel;
    }
    String getName(){
        return name;
    }
    String getTel(){
        return tel;
    }
}
public class PhoneManager {
    public static void main(String[] argv){
        int n;
        Scanner sc = new Scanner(System.in);
        
        System.out.print("인원 수 입력>>");
        n = sc.nextInt();
        Phone[] person = new Phone[n];
        for(int i = 0; i < n; i++){
            System.out.println("이름과 전화번호(번호는 연속적으로 입력)>>> ");
            person[i] = new Phone(sc.next(),sc.next());
        }
        System.out.println("저장되었습니다.");
        
        while(true){
            System.out.print("검색할 이름>>");
            String searchName = sc.next();
            
            for(int i = 0; i < n; i++){
                if(searchName.equals("exit"))
                    System.exit(1);
                else if(searchName.equals(person[i].name)){
                    System.out.println(person[i].getName() + "의 번호는 "+ person[i].getTel());
                    break;
                    }
                else if(!searchName.equals(person[i].name) && i == (n-1))
                    System.out.println(searchName+" 는 없습니다.");
            }
            
        }
    }
}
cs

5. CircleManager는 static 메소드를 가진 클래스이다. StaticTest 클래스는 static 메소드를 활용하는 사례를 보여준다. 실행 결과를 참고하여 코드를 완성하라.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Circle {
    private int radius;
    public Circle(int radius) { this.radius = radius; }
    public int getRadius() { return this.radius; }
    public void setRadius(int radius) { this.radius = radius; }
}
class CircleManager { 
    static void copy(Circle src, Circle dest) { 
        dest.setRadius(src.getRadius()); 
    }
    static boolean equals(Circle a, Circle b) { 
        if (a.getRadius() == b.getRadius())
            return true;
        else
            return false;
    }
}
public class StaticTest {
    public static void main(String[] args) {
        Circle pizza = new Circle(5);
        Circle waffle = new Circle(1);
        
        boolean res = CircleManager.equals(pizza, waffle); 
        if (res == true)
            System.out.println("pizza와 waffle 크기 같음");
        else
            System.out.println("pizza와 waffle 크기 다름");
        
        CircleManager.copy(pizza, waffle); 
        res = CircleManager.equals(pizza, waffle); 
        if (res == true)
            System.out.println("pizza와 waffle 크기 같음");
        else
            System.out.println("pizza와 waffle 크기 다름");
    }
}
cs

6. 다음은 가로 세로로 구성되는 박스를 표현하는 Box 클래스와 이를 이용하는 코드이다. Box의 draw()는 fill 필드에 지정된 문자로 자신을 그린다. 실행 결과를 보면서 코드를 완성하라.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Box {
    private int width, height;
    private char fillChar;
    public Box(){
        this(10,1);
    }
    public Box(int width, int height){
        this.width = width;
        this.height = height;
    }
    public void draw(){
        for(int i=0;i<height;i++){
            for(int j=0;j<width;j++)
                System.out.print(fillChar);
            System.out.println();
        }
    }
    public void fill(char c){
        this.fillChar = c;
    }
    public static void main(String[] args){
        Box a = new Box();
        Box b = new Box(20,3);
        a.fill('*');
        b.fill('%');
        a.draw();
        b.draw();
    }
}
cs

 

참고 문헌 : 명품 자바 에센셜 생능출판 / 황기태



본 게시물은 개인적인 용도로 작성된 게시물입니다. 이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고 개인 공부 목적으로만 이용해주시기 바랍니다.

 

댓글