<명품 JAVA Programming> - Chapter6 실습문제

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

 

<main()>

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("다른 점");
	}

 

<MyPoint>

 


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

 

public class Circle {
	private int x, y;
	private int radius;
	
	public Circle(int x, int y, int radius) {	//생성자
		this.x = x;
		this.y = y;
		this.radius = radius;
	}
	
	public String toString() {	//String 정의
		return "Circle(" + x + "," + y + ")" + "반지름" + radius;
	}
	
	public boolean equals(Object c) {	//equals 정의
		Circle tempC = (Circle)c;
		if(x == tempC.x && y == tempC.y)
			return true;
		else
			return false;
	}
	public static void main(String[] args) {
		Circle a = new Circle(2, 3, 5);	//중심(2,3)에 반지름 5인 원
		Circle b = new Circle(2, 3, 30);	//중심(2,3)에 반지름 30인 원
		System.out.println("원 a: " + a);
		System.out.println("원 b: " + b);
		if(a.equals(b))
			System.out.println("같은 원");
		else
			System.out.println("서로 다른 원");
	}
}

 


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

 

class Calc {
	private int x, y;
	public Calc(int x, int y) {this.x = x; this.y = y;}
	public int sum() {return x + y;}
}

public class MainApp {
	public static void main(String[] args) {
		Calc c = new Calc(10, 20);
		System.out.println(c.sum());
	}
}

 

<Calc 클래스>

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;}
}

 

<MainApp 클래스>

package main;

import chapter6_etc.Calc;

public class MainApp {
	public static void main(String[] args) {
		Calc c = new Calc(10, 20);
		System.out.println(c.sum());
	}
}

 


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

 

class Shape {
	public void draw() {System.out.println("Shape");}
}
class Circle extends Shape {
	public void draw() {System.out.println("Circle");}
}
package chapter6_app;
public class GraphicEditor {
	public static  void main(String[] args) {
		Shape shape = new Q4_Circle();
		shape.draw();
	}
}

 

<수정 후>

 

<Shape 클래스>

package base;

public class Shape {
	public void draw() {System.out.println("Shape");}
}

 

<Circle 클래스>

package derived;

import base.Shape;

public class Circle extends Shape {
	public void draw() {System.out.println("Circle");}
}

 

<GraphicEditor 클래스>

package app;

import base.Shape;
import derived.Circle;

public class GraphicEditor {
	public static  void main(String[] args) {
		Shape shape = new Circle();
		shape.draw();
	}
}

 


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

 

import java.util.Calendar;

public class CurrentTime {
	public static void main(String[] args) {
		Calendar now = Calendar.getInstance();
		int hour = now.get(Calendar.HOUR_OF_DAY);
		int minute = now.get(Calendar.MINUTE);
		
		System.out.println("현재 시간은 " + hour + "시 " + minute + "분입니다.");
		if(4 <= hour && hour < 12)
			System.out.println("Good Morning");
		else if(hour < 18)
			System.out.println("Good Afternoon");
		else if (hour < 22)
			System.out.println("Good Evening");
		else
			System.out.println("Good Night");
	}
}

 


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

 

import java.util.Calendar;
import java.util.Scanner;

public class TimeGame {
	Scanner sc = new Scanner(System.in);
	String str;
	public int run() {
		while(!(str = sc.nextLine()).equals(""));	//엔터키를 입력받으면 종료
		Calendar c = Calendar.getInstance();		//새로운 정보를 받음
		int sec1 = c.get(Calendar.SECOND);			//시작 시각을 저장
		System.out.println("현재 초 시간 = " + sec1);
		
		System.out.print("10초 에상 후 <Enter>키>>");
		while(!(str = sc.nextLine()).equals(""));
		c = Calendar.getInstance();					//새로운 정보를 받음
		int sec2 = c.get(Calendar.SECOND);			//종료 시각을 저장
		System.out.println("현재 초 시간 = " + sec2);
		int result = Math.abs(sec2 - sec1);
		
		sc.close();
		if(sec2 - sec1 < 0) return 60 - result;		//단위가 넘어가면 조정
		return result;
	}
	public static void main(String[] args) {
		TimeGame time = new TimeGame();
		System.out.println("10초에 가까운 사람이 이기는 게임입니다.");

		System.out.print("황기태 시작 <Enter>키>>");
		int Hwang = time.run();
		
		System.out.print("이재문 시작 <Enter>키>>");
		int Lee = time.run();
		
		System.out.print("황기태의 결과 " + Hwang + ",");
		System.out.print("이재문의 결과 " + Lee + ", ");
		if(Math.abs(10 - Hwang) < Math.abs(10 - Lee))
			System.out.println("승자는 황기태");
		else if(Math.abs(10 - Hwang) == Math.abs(10 - Lee))
			System.out.println("무승부");
		else
			System.out.println("승자는 이재문");
	}
}

 


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

 

<StringTokenizer 클래스 이용>

import java.util.Scanner;
import java.util.StringTokenizer;

public class StringToken {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(true) {
			String str = sc.nextLine();
			if(str.equals("그만")) break;
			StringTokenizer st = new StringTokenizer(str);
			System.out.println("어절 개수는 " + st.countTokens());
		}
		System.out.println("종료합니다...");
		sc.close();
	}
}

 

<String 클래스 split()메소드 이용>

import java.util.Scanner;

public class Split {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(true) {
			String str = sc.nextLine();
			if(str.equals("그만")) break;
			String sp[] = str.split(" ");
			System.out.println("어절 개수는 " + sp.length);
		}
		System.out.println("종료합니다...");
		sc.close();
	}
}

 


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

 

import java.util.Scanner;

public class TurnString {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("문자열을 입력하세요. 빈칸이 있어도 되고 영어, 한글 모두 됩니다.");
		String str = sc.nextLine();
		int len = str.length();	//str이 변하므로 길이를 따로 저장
		for(int i = 0; i < len; i++) {
			char toLast = str.charAt(0);	//첫 번째 문자를 따옴
			//두 번재 문자부터 따서 저장. 문자를 추가하기 위해 StringBuffer로 선언
			StringBuffer target = new StringBuffer(str.substring(1));
			target.append(toLast);			//첫 번째 문자를 마지막에 추가
			System.out.println(target);		//생성된 문자열 추가
			str = target.toString();		//String으로 변환해 다음 단계로 넘김
		}
		sc.close();
	}
}

 


9. 철수와 컴퓨터의 가위바위보 게임을 만들어보자. 가위, 바위, 보는 각각 1, 2, 3 키이다. 철수가 키를 입력하면 동시에 프로그램도 Math.Random()을 이용하여 1, 2, 3 중에 한 수를 발생시키고 이것을 컴퓨터가 낸 것으로 한다. 그런 다음 철수와 컴퓨터 중 누가 이겼는지 판별하여 승자를 출력하라.

 

import java.util.Scanner;
public class RSP {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int user, com;

		while(true) {
			System.out.print("철수[가위(1), 바위(2), 보(3), 끝내기(4)]>>");
			user = sc.nextInt();
			com = (int)Math.random()*3 + 1;
			if (user == 4) break;	//4를 입력하면 종료

			String[] what = {"가위", "바위", "보"};
			System.out.print("철수(" + what[user-1] + ") : ");
			System.out.println("컴퓨터(" + what[com-1] + ")");

			int res = user - com;

			switch(res) {
			case 0:	//같은 것을 냈을 때
				System.out.println("비겼습니다."); break;
			case -1:	//가위:바위, 바위:보 -> 철수 패
			case 2:		//보:가위 -> 철수 패
				System.out.println("컴퓨터가 이겼습니다."); break;				
			case -2:	//가위:보 -> 철수 승
			case 1:		//바위:가위, 보:바위 -> 철수 승
				System.out.println("철수가 이겼습니다."); break;
			}
		}
		sc.close();
	}
}

 


10. 갬블링 게임을 만들어보자. 두 사람이 게임을 진행한다. 이들의 이름을 키보드로 입력받으며 각 사람은 Person 클래스로 작성하라. 그러므로 프로그램에는 2개의 Person 객체가 생성되어야 한다. 두 사람은 번갈아 가면서 게임을 진행하는데 각 사람이 자기 차레에서 <Enter> 키를 입력하면, 3개의 난수가 발생되고 이 숫자가 모두 같으면 승자가 되고 게임이 끝난다. 난수의 범위를 너무 크게 잡으면 3개의 숫자가 일치하게 나올 가능성이 적기 때문에 숫자의 범위는 1~3까지로 한다.

 

import java.util.Scanner;
import java.util.Random;

class Person {
	Scanner sc = new Scanner(System.in);
	Random r = new Random();
	private String name;
	private String str;
	private int [] num = new int[3];
	public Person(String name) {
		this.name = name;
	}
	public String get() {
		return this.name;
	}
	public boolean run() {
		System.out.println("[" + this.name + "]: <Enter>");
		while(!(str = sc.nextLine()).equals(""));	//엔터키를 입력받으면 종료
		for(int i = 0; i < 3; i++) {
			num[i] = r.nextInt(3) + 1;			//랜덤 생성
			System.out.print(num[i] + "  ");
		}
		if(num[0] == num[1] && num[1] == num[2] && num[2] == num[0]) 
			return true;	//모두 같으면 true 리턴
		return false;
	}
}
public class Gambling {
	public static void main(String[] args) {
		boolean res;
		Scanner sc = new Scanner(System.in);
		System.out.print("1번째 선수 이름>>");
		String name = sc.next();
		Person P1 = new Person(name);
		System.out.print("2번째 선수 이름>>");
		name = sc.next();
		Person P2 = new Person(name);

		while(true) {
			res = P1.run();
			if(res) {
				System.out.println("\t" + P1.get() + "님이 이겼습니다!"); 
				break;
			}
			else System.out.println("아쉽군요!");
			
			res = P2.run();
			if(res) {
				System.out.println("\t" + P2.get() + "님이 이겼습니다!");
				break;
			}
			else System.out.println("아쉽군요!");
		}
		sc.close();
	}
}

 


11.  StringBuffer 클래스를 활용하여 명령처럼 문자열을 수정하라. 첫 번째 만난 문자열만 수정한다.

 

package chapter6;
import java.util.Scanner;

public class Revise {
	public static void main(String[] args) {
		System.out.print(">>");
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		StringBuffer sb = new StringBuffer(str);
		
		while(true) {
			System.out.print("명령: ");
			String order = sc.nextLine();
			if(order.equals("그만")) {
				System.out.print("종료합니다.");
				break;
			}
			String [] tokens = order.split("!");
			if(tokens.length != 2)	//두 토큰으로 나누어지지 않을 때
				System.out.println("잘못된 명령입니다.");
			else	//토큰 한 쪽이 비었을 때
				if(tokens[0].length() == 0 || tokens[1].length() == 0) {
					System.out.println("잘못된 명령입니다!");
					continue;
				}
			
			int index = sb.indexOf(tokens[0]);	//없으면 -1 반환
			if(index == -1) {
				System.out.println("찾을 수 없습니다!");
				continue;
			}
			//첫번째 토큰이 있던 자리를 두 번째 토큰으로 대체
			sb.replace(index, index+tokens[0].length(), tokens[1]);
			System.out.println(sb.toString());
		}
		sc.close();
	}
}

 


12. 문제 10의 갬블링 게임을 n명이 하도록 수정하라. 실행 예시와 같이 게임에 참여하는 선수의 수를 입력받고 각 선수의 이름을 입력받도록 수정하라.

 

import java.util.Scanner;
import java.util.Random;

class Person {
	Scanner sc = new Scanner(System.in);
	Random r = new Random();
	private String name;
	private String str;
	private int [] num = new int[3];
	public Person(String name) {
		this.name = name;
	}
	
	public String get() {
		return this.name;
	}
	public boolean run() {
		System.out.println("[" + this.name + "]: <Enter>");
		while(!(str = sc.nextLine()).equals(""));	//엔터키를 입력받으면 종료
		for(int i = 0; i < 3; i++) {
			num[i] = r.nextInt(3) + 1;			//랜덤 생성
			System.out.print(num[i] + "  ");
		}
		if(num[0] == num[1] && num[1] == num[2] && num[2] == num[0]) 
			return true;	//모두 같으면 true 리턴
		return false;
	}
}
public class nGambling {
	public static void main(String[] args) {
		boolean res;
		String name;
		Scanner sc = new Scanner(System.in);
		System.out.print("겜블링 게임에 참여할 선수 숫자>>");
		int n = sc.nextInt();
		Person P [] = new Person[n];	//객체 배열 생성
		for(int i = 0; i < n; i++) {
			System.out.print((i + 1) + "번째 선수 이름>>");
			name = sc.next();
			P[i] = new Person(name);
		}

		int i = 0;
		while(true) {
			res = P[i].run();
			if(res) {
				System.out.println("\t" + P[i].get() + "님이 이겼습니다!"); 
				break;
			}
			else System.out.println("아쉽군요!");
			i++;
			if(i == n) i = 0;	//4명 모두 반복하면 다시 시작
		}
		sc.close();
	}
}