본문 바로가기

[책]명품 JAVA Programming

명품 자바 프로그래밍 4장 OpenChallenge&실습문제

OpenChallenge [끝말잇기 게임]

1. 참가자 수를 정하고 이름을 정한다.

2. 시작 단어는 아버지 이다.

3. Player 클래스를 따로 작성하자.

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
48
49
50
51
52
53
54
55
56
57
58
import java.util.Scanner;
 
public class OpenChallenge {
 
    public static void main(String[] args) {
        System.out.println("끝말잇기 게임을 시작합니다...");
        Scanner sc = new Scanner(System.in);
        
        System.out.print("게임에 참가하는 인원은 몇명 입니까>>");
        int player_num = sc.nextInt();
        
        Player[] player = new Player[player_num];    //입력받은 플레이어 수만큼 Player 객체 생성.
        
        for(int i =0; i<player.length; i++) {
            System.out.print("참가자의 이름을 입력하세요>>");
            String name = sc.next();
            player[i] = new Player();
            player[i].setName(name);
        }
        
        System.out.println("시작하는 단어는 아버지입니다.");
        String word = "아버지";
        boolean flag = true;
        while(flag) {
            
            for(int i=0; i<player.length; i++) {
                System.out.println(player[i].getName()+">>");
                String word2 = sc.next();
                int lastIndex = word.length() - 1;        //마지막 문자의 자리수
                char lastChar = word.charAt(lastIndex);        //마지막 문자. 지금은 "지"
                char firstChar = word2.charAt(0);        //첫번째 문자
                
                if(firstChar==lastChar) {
                    word = word2;
                }else {
                    System.out.println(player[i].getName()+"이(가) 졌습니다.");
                    flag = false;
                    break;
                }
                
            }
            
        }
    }
 
}
 
class Player {
    String name;
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}
cs

 

실습문제

 

1. 자바 클래스 작성연습. 예시와 같이 출력 되도록 작성.

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
class TV{
    private String name;
    private int year;
    private int inch;
    
    public TV(String name,int year,int inch) {
        this.name=name;
        this.year=year;
        this.inch=inch;
        
    }
    
    public void show() {
        System.out.println(name+"에서 만든 "+ year+"년형 "+inch+"인치 TV");
    }
    
}
 
 
public class q1 {
 
    public static void main(String[] args) {
        TV myTV=new TV("LG",2017,32);
        myTV.show();
 
    }
 
}
cs

2. Grade 클래스를 작성 하자. 3 과목의 점수를 입력받아 객체를 생성하고 성적 평균을 출력.

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
import java.util.Scanner;
 
class Grade{
    private int math;
    private int science;
    private int english;
    
    public Grade(int math,int science,int english) {
        this.math=math;
        this.science=science;
        this.english=english;
    }
    
    public int avg() {
        return (math+science+english)/3 ;
    }
}
 
public class q2 {
 
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        
        System.out.print("수학, 과학, 영어 순으로 3개의 점수 입력>>");
        int math=sc.nextInt();
        int science=sc.nextInt();
        int english=sc.nextInt();
        Grade me=new Grade(math, science, english);
        System.out.println("평균은 "+me.avg());
        
        sc.close();
    }
 
}
cs

3. 노래 한곡을 나타내는 Song 클래스를 작성하라. title, artist, year, country변수를 가짐. 생성자2, show() 메소드를 가짐.

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
class Song{
    private String title;
    private String artist;
    private int year;
    private String country;
    
    public Song() {};    //디폴트 생성자
    
    public Song(String title,String artist,int year,String country) {        //변수 초기화 생성자
        this.title=title;
        this.artist =artist;
        this.year=year;
        this.country=country;
    }
    
    
    
    void show() {
        System.out.println(year+"년 "+country+"국적의 "+artist+"이(가) 부른 "+title);
    }
    
}
 
public class q3 {
 
    public static void main(String[] args) {
        String title ;
        String artist;
        int year;
        String country;
        
        Song song=new Song("Dancing Queen","ABBA",1978,"스웨덴");
        song.show();
        
 
    }
 
}
 
cs

4. 직사각형을 표현하는 Rectangle 클래스를 작성.

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
class Rectangle{
    private int x,y,width,height;
    
    public Rectangle(int x,int y,int width, int height) {
        this.x=x;
        this.y=y;
        this.width=width;
        this.height=height;
    }
    
    public int square() {
        return width*height;
    }
    public void show() {
        System.out.println("("+x+","+y+")에서 크기가  "+ width+"X"+height+"인 사각형");
    }
    
    public boolean contains(Rectangle r) {        //충돌처리 할때도 요긴하게 쓰입니다. 중학교 수학 정도면 작성 가능!
        if((this.x<r.x)&&(this.y<r.y)&&(this.x+this.width>r.x+r.width) && (this.y+this.height > r.y+r.height ))
            return true;
        else
            return false;
    }
    
}
public class q4 {
 
    public static void main(String[] args) {
        Rectangle r=new Rectangle(2,2,8,7);
        Rectangle s=new Rectangle(5,5,6,6);
        Rectangle t=new Rectangle(1,1,10,10);
        
        r.show();
        System.out.println("s의 면적은"+s.square());
        if(t.contains(r))
            System.out.println("t는 r을 포함합니다. ");
        
        if(t.contains(s))
            System.out.println("t는 s를 포함합니다. ");
    }
 
}
cs

5. Circle 클래스와 CircleManager 클래스를 완성하라.

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
import java.util.Scanner;
 
class Circle{
    private double x, y;
    private int radius;
    public Circle(double x, double y, int radius) {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }
    public void show() {
        System.out.println("("+x+","+y+")"+radius);
    }
}
 
public class Q05 {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Circle c [] = new Circle[3];
        for(int i=0; i<c.length;i++) {
            System.out.print("x, y, radius >>");
            double x = sc.nextDouble();
            double y = sc.nextDouble();
            int radius = sc.nextInt();
            c[i] = new Circle(x,y,radius);
        }
        
        for(int i=0; i<c.length;i++) {
            c[i].show();
        }
        sc.close();
    }
 
}
cs

6. 앞의 5번 문제는 정답이 공개되어 있다. 이 정답을 참고하여 Circle 클래스와 CircleManager 클래스를 수정해라.

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
48
49
50
51
import java.util.Scanner;
 
class Circle_next{
    private double x, y;
    private int radius;
    public Circle_next(double x, double y, int radius) {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }
    public void show() {
        System.out.println("("+x+","+y+")"+radius);
    }
    public int getRadius() {
        return radius;
    }
    public double getX() {
        return x;
    }
    public double getY() {
        return y;
    }
}
 
public class Q06 {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Circle_next c [] = new Circle_next[3];
        for(int i=0; i<c.length;i++) {
            System.out.print("x, y, radius >>");
            double x = sc.nextDouble();
            double y = sc.nextDouble();
            int radius = sc.nextInt();
            c[i] = new Circle_next(x,y,radius);
        }
        int maxR = c[0].getRadius();
        double maxX=0,maxY=0;
        for(int i=0; i<c.length;i++) {
            int r = c[i].getRadius();
            if(maxR<=r) {
                maxR = r;
                maxX = c[i].getX();
                maxY = c[i].getY();
            }
        }
        System.out.println("가장 면적이 큰 원은 ("+maxX+","+maxY+")"+maxR);
        sc.close();
    }
 
}
cs

7. 하루의 할 일을 표현하는 클래스 Day는 다음과 같다. 한 달의 할 일을 표현하는 클래스를 작성하라.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.Scanner;
 
class  Day{
    private String work;        
    public void set(String work) { this.work=work;}
    public String get() {return work;}
    public void show() {
        if(work==null)
            System.out.println("없습니다.");
        else
            System.out.println(work+"입니다. ");
    }
}
 
class MonthSchedule{
    private int x;
    Day[] day;
    int dayNum;
    boolean flag=true;
    
    Scanner sc=new Scanner(System.in);
    
    public MonthSchedule(int x) {
        dayNum=x;
        day=new Day[dayNum];        
        for(int i=0;i<day.length;i++) {
            day[i]=new Day();
        }
    }
    
    public void input() {
        System.out.print("날짜(1~30)?");
        int i=sc.nextInt();
        System.out.print("할일(빈칸없이입력)?");
        String work=sc.next();
        day[i-1].set(work);    
    }                                
    
    public void view() {
        System.out.print("날짜(1~30)?");
        int i=sc.nextInt();
        System.out.print(i+"일의 할 일은 ");
        day[i-1].show();
    }
    
    public void finish() {
        System.out.println("프로그램을 종료합니다.");
        flag=false;
    }
    
    public void run() {
        int option;
        System.out.println("이번달 스케쥴 관리 프로그램.");
        while(flag) {
            System.out.print("할일(입력:1, 보기:2, 끝내기3:) >>");
            option=sc.nextInt();
            switch(option) {
            case 1:
                input();
                break;
            case 2:
                view();
                break;
            case 3:
                finish();
                break;
            default:
                System.out.println("제대로 입력하세요!");
            }
            System.out.println();
        }
    }
}
public class q7 {
 
    public static void main(String[] args) {
        MonthSchedule april=new MonthSchedule(30);
        april.run();
    }
 
}
cs

8. 이름, 전화번호 필드와 생성자 등을 가진 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
48
49
50
51
52
53
54
55
import java.util.Scanner;
 
class Phone{
    private String name;
    private String tel;
    
    public Phone(String name, String tel) {
        this.name = name;
        this.tel = tel;
    }
    
    public String getName() {
        return name;
    }
    public String getTel() {
        return tel;
    }
}
 
public class q8{
    public static void main(String[] args) {
        System.out.print("인원수>>");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        Phone[] phones = new Phone[num];
        
        for (int i=0; i<num; i++) {
            System.out.print("이름과 전화번호(이름과 번호는 빈 칸 없이 입력)>>");
            String name = sc.next();
            String tel = sc.next();
            phones[i] = new Phone(name,tel);
        }
        System.out.println("저장되었습니다...");
        
        while(true) {
            System.out.print("검색할 이름>>");
            String search = sc.next();
            if(search.equals("그만")) {
                break;
            }
            
            for(int i = 0;i<num;i++) {
                if(search.equals(phones[i].getName())) {
                    System.out.println(phones[i].getName()+"의 번호는 "+phones[i].getTel()+" 입니다.");
                    break;
                }
                if(i==num-1) {
                    System.out.println(search+"이(가) 업습니다.");
                }
            }
        }
        
        sc.close();
    }
}
cs

9. 다음 2개의 static 가진 클래스를 만들어보자. concat()와 print()를 작성해 클래스를 완성하라.

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
class ArrayUtil{
        public static int [] concat(int[] a,int[] b) {
            int i=0;
            int c[]=new int[(a.length+b.length)];
            for(i=0;i<a.length;i++) {
                c[i]=a[i];
            }
            for(int j=0;j<b.length;j++) {
                c[i+j]=b[j];
            }
            return c;
        }
        public static void print(int[] a) {
            System.out.print("{");
            for(int i=0;i<a.length;i++) {
                System.out.print(a[i]+" ");
            }
            System.out.print("}");
        }
    }
 
public class q9 {
        public static void main(String[] args) {
            int [] array1= {1,5,7,9};
            int [] array2= {3,6,-1,100,77};
            int [] array3=ArrayUtil.concat(array1, array2);
            ArrayUtil.print(array3);
        }
}
cs

10. Dictionary 클래스가 있다. kor2Eng() 메소드와 실행 클래스를 작성하라.

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
import java.util.Scanner;
 
class Dictionary {
    Scanner sc=new Scanner(System.in);
    private static String [] kor = { "사랑""아기""돈""미래""희망" };
    private static String [] eng = { "love""baby""money""future""hope" };
    
    public static String kor2Eng(String word) { 
        for(int i=0;i<5;i++) {
            if(word.equals(kor[i])) {
                System.out.println(eng[i]);
                break;
            }if(i==4) {
                System.out.println(word+"는 사전에 없습니다.");
            }
        }
        return null;
        
    }
    
}
 
 
public class q10 {
 
    public static void main(String[] args) {
        System.out.println("한영 단어 검색 프로그램 입니다.");
        Scanner sc = new Scanner(System.in);
        Dictionary dic = new Dictionary();
        
        while(true) {
            System.out.print("한글단어?");
            String word = sc.next();
            if(word.equals("그만"))
                break;
            dic.kor2Eng(word);
            
        }
        sc.close();
 
    }
}
cs

11. 다수의 클래스를 만들고 활용하는 연습을 해보자. +,-,/,* 를 수행하는 클래스를 만들고 출력하라.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.Scanner;
 
class Add{
    private int a,b;
    
    void setValue(int a,int b) {
        this.a=a;
        this.b=b;
    }
    public int calculate() {
        return a+b;
    }
    
}
 
class Sub{
    private int a,b;
    
    void setValue(int a,int b) {
    this.a=a;
    this.b=b;
    }
    public int calculate() {
    return a-b;
    }
}
 
class Mul{
private int a,b;
    
    void setValue(int a,int b) {
    this.a=a;
    this.b=b;
    }
    public int calculate() {
    return a*b;
    }
}
 
class Div{
private int a,b;
    
    void setValue(int a,int b) {
    this.a=a;
    this.b=b;
    }
    public double calculate() {
        return (double)a/b;
    }
}
 
 
 
public class q11 {
 
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.print("두 정수와 연산자를 입력하시오>>");
        int a=sc.nextInt();
        int b=sc.nextInt();
        String cal=sc.next();
        
        switch(cal) {
        case "+":
            Add add=new Add();
            add.setValue(a,b);
            System.out.println(add.calculate());
            break;
        case "-":
            Sub sub=new Sub();
            sub.setValue(a, b);
            System.out.println(sub.calculate());
            break;
        case "*":
            Mul mul=new Mul();
            mul.setValue(a, b);
            System.out.println(mul.calculate());
            break;
        case "%":
            Div div=new Div();
            div.setValue(a, b);
            System.out.println(div.calculate());
            break;
        default :
            System.out.print("제대로 입력하세요.");
            
            
        }
    }
 
}
 
cs

12. 콘서트 예약 시스템을 만들어보자. 기능 구현을 해보자! (어려우면 넘기세요 나중에 할 수 있습니다.)

스스로 해보는걸 추천하지만 너무 스트레스 받으면 안하셔도 됩니다. 나중엔 할 수 있을거에요! 질문은 댓글 남겨주세요.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import java.util.Scanner;
 
 
class Consert{
    String[] Sseat;
    String[] Aseat;
    String[] Bseat;
    Scanner sc = new Scanner(System.in);
    
    public Consert() {        //처음 만들떄 생성자.
        //처음 의자 초기화 각 10개씩
                Sseat = new String[10];
                Aseat = new String[10];
                Bseat = new String[10];
                String init = "---";
                for(int i=0; i<10; i++) {
                    Sseat[i]=init;
                    Aseat[i]=init;
                    Bseat[i]=init;
                }
        }
    
    public void printSeat(String[] seat) {
        for(int i=0; i<seat.length; i++) {
            System.out.print(seat[i]+" ");
        }
    }
    
    public void book(int seatNum) {
        
        if(seatNum == 1) {
            printSeat(Sseat);
            System.out.print("\n이름>>");
            String name = sc.next();
            System.out.print("번호>>");
            int num = sc.nextInt();
            int realnum = num-1;
 
            if(Sseat[realnum].equals("---")) {
                Sseat[realnum]=name;
            }else {
                System.out.println("이미 있는 자리 입니다.");
            }
        }else if(seatNum ==2) {
            printSeat(Aseat);
            System.out.print("\n이름>>");
            String name = sc.next();
            System.out.print("번호>>");
            int num = sc.nextInt();
            int realnum = num-1;
            
            if(Aseat[realnum].equals("---")) {
                Aseat[realnum]=name;
            }else {
                System.out.println("이미 있는 자리 입니다.");
            }
        }else if(seatNum ==3) {
            printSeat(Bseat);
            System.out.print("\n이름>>");
            String name = sc.next();
            System.out.print("번호>>");
            int num = sc.nextInt();
            int realnum = num-1;
            
            if(Bseat[realnum].equals("---")) {
                Bseat[realnum]=name;
            }else {
                System.out.println("이미 있는 자리 입니다.");
            }
        }
        
    }
    
    public void showAll() {
        System.out.print("S>>");
        printSeat(Sseat);
        System.out.print("\nA>>");
        printSeat(Aseat);
        System.out.print("\nB>>");
        printSeat(Bseat);
        System.out.println("\n<<<조회를 완료하였습니다.>>>");
    }
    
    public void cancle(int seatNum) {
        switch(seatNum) {
        case 1:
            System.out.print("S>>");
            printSeat(Sseat);
            System.out.println();
            System.out.print("이름>>");
            String name = sc.next();
            
            for(int i=0; i<10; i++) {
                if(Sseat[i].equals(name)){
                    Sseat[i]="---";
                    break;
                }
            }
            break;
        case 2:
            System.out.print("A>>");
 
            printSeat(Aseat);
            System.out.println();
            System.out.print("이름>>");
            String name2 = sc.next();
            
            for(int i=0; i<10; i++) {
                if(Aseat[i].equals(name2)){
                    Aseat[i]="---";
                    break;
                }
            }
            break;
        case 3:
            System.out.print("B>>");
            printSeat(Bseat);
            System.out.println();
            System.out.print("이름>>");
            String name3 = sc.next();
            
            for(int i=0; i<10; i++) {
                if(Bseat[i].equals(name3)){
                    Bseat[i]="---";
                    break;
                }
            }
            break;
        }
    }
}
        
 
public class q12{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Consert consert = new Consert();
        System.out.println("명품콘서트홀 예약 시스템입니다.");
        boolean flag = true;
        while(flag) {
            System.out.print("예약:1, 조회:2, 취소:3, 끝내기:4 >>");
            int choose = sc.nextInt();
            
            switch(choose) {
            case 1:
                System.out.print("좌석구분 S(1), A(2), B(3)>> ");
                int seatNum = sc.nextInt();
                consert.book(seatNum);
                break;
            case 2:
                consert.showAll();
                System.out.println();
                break;
            case 3:
                System.out.print("좌석 S:1, A:2, B:3>>");
                int seatNum2 = sc.nextInt();
                consert.cancle(seatNum2);
                break;
            case 4:
                flag = false;
            }
        
        }
        sc.close();
    }
}
cs