프로그래밍 언어/JAVA

<Java> 명품 Java Programming 실습문제 6장 1 - 8

창조적생각 2021. 7. 13. 17:12

1. 다음 main()이 실행되면 아래 예시와 같이 출력되도록 MyPoint 클래스를 작성하라.

 

1
2
3
4
5
6
7
8
9
10
11
    public static void main(String[] args) {
        
        MyPoint p = new MyPoint(3,50);
        MyPoint q = new MyPoint(4,50);
        System.out.println(p);
        if(p.equals(q))
            System.out.println("같은점");
        else
            System.out.println("다른점");
        
 
cs

[실행결과]

Point(3,50)
다른점

 

[풀이]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyPoint{
    int x;
    int y;
     MyPoint(int x, int y){
    this.x = x;
    this.y = y;
    }
     public String toString() {
         return "Point("+x+","+y+")";
     }
     public boolean equals(Object obj) {
         MyPoint r = (MyPoint)obj;
         if(x == r.x && y == r.y) return true;
         else return false;
     }
}
cs

 

2. 중심을 나타내는 정수 x,y와 반지름 radius 필드를 가지는 Circle 클래스를 작성하고자 한다. 생성자는 3개의 인자(x,y,radius)를 받아 해당 필드를 초기화하고 equals() 메소드는 두 개의 Circle 객체의 중심이 같으면 같은 것으로 판별하도록 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Circle a = new Circle(2,3,5);
        Circle b = new Circle(2,3,30);
        System.out.println("원 a :"+ a);
        System.out.println("원 b :"+ b);
        if(a.equals(b))
            System.out.println("같은 원");
        else
            System.out.println("서로다른 원");
    }
 
}
 
cs

[실행결과]

원 a :Circle(2,3) 반지름5
원 b :Circle(2,3) 반지름30
같은 원

 

[풀이]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Circle {
    int x;
    int y;
    int r;
    public Circle(int x, int y, int r) {
        this.x = x;
        this.y = y;
        this.r = r;
    }
    public String toString() {
        return "Circle("+x+","+y+") 반지름"+r;
    }
    
    public boolean equals(Object obj) {
        Circle c = (Circle)obj;
        if(x == c.x && y ==  c.y)
            return true;
        else return false;
        
    }
}
cs

 

3. 다음 코드를 수정하여, Calc 클래스는 etc 패키지에, MainApp 클래스는 main 패키지에 분리 작성하라.

[풀이]

etc 패키지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package etc;
 
public class Calc {
    private int x,y;
    public Calc(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int sum() {
        return x+y;
    }
 
}
 
cs

main 패키지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main;
 
import etc.Calc;
 
public class MainApp {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Calc c = new Calc(10,20);
        System.out.println(c.sum());
    }
 
}
 
cs

4. 다음 코드를 수정하여 Shape 클래스는 base 패키지에, Circle 클래스는 derived 패키지에, GraphicEditor 클래스는 app 패키지에 분리 작성하라.

[풀이]

 

1
2
3
4
5
6
7
8
9
package base;
 
public class Shape {
    public void draw() {
        System.out.println("Shape");
    }
 
}
 
cs

 

1
2
3
4
5
6
package derived;
import base.Shape;
public class Circle extends Shape {
public void draw() {System.out.println("Circle");}    
}
 
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
package GraphicEditor;
import base.Shape;
import derived.Circle;
public class app {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Shape shape = new Circle();
        shape.draw();
    }
 
}
 
cs

 

5. Calendar 객체를 생성하면 현재 시간을 알 수 있다. 프로그램을 실행한 현재 시간이 새벽 4시에서 낮 12시 이전이면 "good Mornig"을 오후 6시 이전이면 "Good Afternoon"을, 밤 10시 이전이면 "Good Evening"을, 그 이후에는 "Good Night"을 출력하는 프로그램을 작성하라.

 

[실행결과]

현재 시간은5시 10입니다.
Good Afternoon!

 

[풀이]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package Practice6_5;
import java.util.Calendar;
public class A5 {
public static void printCalendar(Calendar cal) {
    int hour = cal.get(Calendar.HOUR);
    int ampm = cal.get(Calendar.AM_PM);
    int hourofDay = cal.get(Calendar.HOUR_OF_DAY);
    int minute = cal.get(Calendar.MINUTE);
    System.out.println("현재 시간은"+hour+"시 "+minute+"입니다.");
    if(4 <= hourofDay && hourofDay < 12)
        System.out.print("Good Mornig!");
    else if(12 <= hourofDay && hourofDay < 18)
        System.out.print("Good Afternoon!");
    else System.out.print("Good Night!");
}
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Calendar now = Calendar.getInstance();
        printCalendar(now);
    }
 
}
 
cs

6.경과시간을 맞추는 게임을 작성하라. 다음 예시를 참고하면,<enter> 키를 입력하면 현재 초 시간을 보여주고 여기서 10초에 더 근접하도록 <Enter> 키를 입력한 사람이 이기는 게임이다.

 

<풀이>

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
package Practice06;
 
import java.util.Calendar;
import java.util.Scanner;
 
public class Practice06_06 {
    public static int run(String name) {
        Scanner s = new Scanner(System.in);
        
        int start, end, result;
        
        System.out.print(name + " 시작 <Enter>키 >> ");
        s.nextLine();
        start = Calendar.getInstance().get(Calendar.SECOND);
        System.out.println("   현재 초 시간 = " + start); 
        
        System.out.print("10초 예상 후 <Enter>키 >> ");
        s.nextLine();
        end = Calendar.getInstance().get(Calendar.SECOND);
        System.out.println("   현재 초 시간 = " + end);
        
        result = start - end;
        if (result < 0) result = Math.abs(result);
        else result = 60 - result;
        return result;
    }
    
    public static void main(String[] args) {
        int aScore, bScore;
        String aName = "황기태", bName = "이재문";
        
        System.out.println("10초에 가까운 사람이 이기는 게임입니다.");
        
        aScore = run(aName);
        bScore = run(bName);
        
        System.out.print(aName + "결과 " + aScore + "," + bName + "결과 " + bScore + ",");
        if (Math.abs(aScore-10< Math.abs(bScore-10)) System.out.println("승자는 " + aName);
        else System.out.println("승자는 " + bName);
    }
 
}
 
cs

7.Scanner를 이용하여 한 라인을 읽고, 공백으로 분리된 어절이 몇 개 들어 있는지 "그만"을 입력할 때까지 반복하는 프로그램을 작성하라.

 

[실행결과]

I Love You
어절 개수는3
자바는 객체 지향 언어로서 매우 좋은 언어이다.
어절 개수는7
그만

 

(1)StringTokenizer 클래스를 이용하여 작성하라.

[풀이]

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
package practice6_7;
import java.util.Scanner;
import java.util.StringTokenizer;
public class answer6_7 {
    String s;
    public boolean equals(Object obj) {
    answer6_7 an = (answer6_7)obj;
    if(s == "그만"return false;
    else return true;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        String s;
        
        while(true) {
            
        StringTokenizer st = new StringTokenizer(s= scanner.nextLine()," ");
        if(s.equals("그만"))
            break;
        System.out.println("어절 개수는"+st.countTokens());
        
        
        }
    }
 
}
 
cs

 

(2)String 클래스의 split()메소드를 이용하여 작성하라.

[풀이]

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
package practice6_7;
import java.util.Scanner;
public class answer6_7_2 {
    String s;
    public boolean equals(Object obj) {
    answer6_7 an = (answer6_7)obj;
    if(s == "그만"return false;
    else return true;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s;
        int cnt = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print(">>");
        while(true) {
            s = scanner.nextLine();
            if(s.equals("그만"))
                break;
            String sl[] = s.split(" ");
            for (int i = 0; i<sl.length;i++)
                cnt++;
                System.out.println("어절 개수는"+cnt);
                cnt = 0;
        }
    }
 
}
 
cs

8. 문자열을 입력받아 한 글자씩 회전시켜 모두 출력하는 프로그램을 작성하라.

[실행 결과]

문자열을 입력하세요. 빈 칸이 있어도 되고 영어 한글 모두 됩니다.

I Love You
 Love YouI
Love YouI 
ove YouI L
ve YouI Lo
e YouI Lov
 YouI Love
YouI Love 
ouI Love Y
uI Love Yo
I Love You

[풀이]

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
package practice6_8;
import java.util.Scanner;
public class answer6_8 {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        String s;
        String S1;
        String S2;
        
        System.out.println("문자열을 입력하세요. 빈 칸이 있어도 되고 영어 한글 모두 됩니다.");
        s = scanner.nextLine();
        while(true) {
            for(int i = 0; i<s.length();i++) {
                S1 = s.substring(i);
                StringBuffer sb = new StringBuffer(S1);
                StringBuffer sb1 = new StringBuffer(s);
                sb1.setLength(i);
                sb.append(sb1);
                System.out.println(sb);
            }
        }
    }
 
}
 
cs

 

728x90