본문 바로가기

명품 자바 프로그래밍

명품 자바 프로그래밍 6장 실습 문제

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

class MyPoint {
	// 지역변수
	int x;
	int y;
	// 생성자
	public MyPoint(int x,int y) {
		this.x = x;
		this.y = y;
	}
	// toString()
	public String toString() {
		return "Point(" + x + "," + y +")";
	}
}

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

 

 

 

2. x,y,radius를 가지는 Circle클래스 작성.

class Circle {
	int x,y,radius;
	
	// 생성자
	public Circle(int x, int y, int r) {
		this.x = x;
		this.y = y;
		this.radius = r;
	}
	// toString()
	public String toString() {
		return "Circle(" + x + "," + y + ")반지름" + radius;
	}
	// equals()가 x,y,radius 3개의 멤버를 비교하지말고, x,y만 비교하도록 오버라이딩
	boolean equals(Circle circle) {
		if (this.x == circle.x && this.y == circle.y)
			return true;
		else
			return false;
	}
}

public class Main {
	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클래스는 main패키지로 분리작성하라.

 

 1) Calc클래스

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

 

 2) main패키지

package ex03_main;

import ex03_etc.Calc;

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

 

 

 

4. 다음 코드 수정하여 Shape클래스는 base패키지에 ~~~~ 분리 작성하라.

 

 1) Shape클래스

package ex04_base;

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

 

 2) Circle클래스

package ex04_derived;

import ex04_base.Shape;

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

 

 

 3) GraphicEditor클래스

package ex04_app;

import ex04_base.Shape;
import ex04_derived.Circle;

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

 

 

 

5. Calendar객체를 생성하면 현재 시간을 알 수 있다. 프로그램을 작성하라.

package ex05;
import java.util.Calendar;

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

 

 

 

6. 경과시간 맞추는 게임을 작성하라.

package ex06;
import java.util.*;



public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int hs1 = 0, hs2 = 0, result1 = 0;
		int ls1 = 0, ls2 = 0, result2 = 0;
		String winner;
		
		System.out.println("10초에 가까운 사람이 이기는 게임입니다.");
		
		
		System.out.print("황기태 시작 <Enter>키 >> ");
		if ( s.nextLine().isEmpty() )	{
			Calendar now1 = Calendar.getInstance();
			hs1 = now1.get(Calendar.SECOND);
			System.out.println("	현재 초 시간 = " + hs1);
		}
		System.out.print("10초 예상 후 <Enter>키 >> ");
		if ( s.nextLine().isEmpty() )	{
			Calendar now2 = Calendar.getInstance();
			hs2 = now2.get(Calendar.SECOND);
			System.out.println("	현재 초 시간 = " + hs2);
		}
		
		System.out.print("이재문 시작 <Enter>키 >> ");
		if ( s.nextLine().isEmpty() )	{
			Calendar now3 = Calendar.getInstance();
			ls1 = now3.get(Calendar.SECOND);
			System.out.println("	현재 초 시간 = " + ls1);
		}
		System.out.print("10초 예상 후 <Enter>키 >> ");
		if ( s.nextLine().isEmpty() )	{
			Calendar now4 = Calendar.getInstance();
			ls2 = now4.get(Calendar.SECOND);
			System.out.println("	현재 초 시간 = " + ls2);
		}
		
		// 황기태 결과 구하기
		if (hs1>hs2)	
			result1 = hs2+60 - hs1;
		else 			
			result1 = hs2 - hs1;
		// 이재문 결과 구하기
		if (ls1>ls2)	
			result2 = ls2+60 - ls1;
		else 			
			result2 = ls2 - ls1;
		// s1과 s2사이의 시간차를 먼저 결과로 출력
		System.out.print("황기태의 결과 " + result1 + ", 이재문의 결과 " + result2);
		
		// 단순하게 s1과 s2간의 시간차로 승자를 구할 경우,
		// 패자와 승자가 뒤바뀌는 상황이 발생 가능
		// 따라서, 10을 뺀 뒤 절댓값이 작은 사람을 최종승자로 출력할 에정.
		result1 = Math.abs(result1-10);
		result2 = Math.abs(result2-10);
		if (result1>result2)	winner = "이재문";
		else					winner = "황기태";
		
		System.out.println(", 승자는 " + winner);
		s.close();
	}
}

 

 

 

7. Scanner이용하여 한줄을 읽고, 어절이 몇개인지 "그만"입력할때까지 반복되는 프로그램 작성

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		
		// StringTokenizer 활용
		while(true) {
			System.out.print(">> ");
			String input = s.nextLine();
			if (input.equals("그만")) break;
			
			// 토큰화 후 갯수 파악
			StringTokenizer st = new StringTokenizer(input);
			System.out.println("어절 개수는 " + st.countTokens());
		}
		/*
		// split() 활용
		while(true) {
			System.out.print(">> ");
			String input = s.nextLine();
			if (input.equals("그만")) break;
			
			// 나눈 뒤 어절 갯수 파악
			String word[] = input.split(" ");
			System.out.println("어절 개수는 " + word.length);
		}
		*/
		System.out.println("종료합니다...");
		s.close();
	}
}

 

 

 

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

import java.util.*;

public class Main {
	public static void main(String[] args) {
		
		Scanner s = new Scanner(System.in);
		System.out.println("문자열을 입력하세요."
						 + "빈칸이 있어도 되고 영어 한글 모두 됩니다.");	
		String input = s.nextLine();
		int len = input.length();
		// 1-9/0
		// 2-9/0-1
		// 3-9/0-2
		// 이런식으로 출력되어야 함.
		// substring(x,y)는 x인덱스부터 y-1번째 인덱스까지임을 주의
		for(int i = 1; i<=len; i++) {
			String r = input.substring(i,len) + input.substring(0,i);
			System.out.println(r);
		}
		s.close();
	}

}

 

 

 

9. 철수와 컴퓨터의 가위바위보 게임을 만들어보자

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		while(true) {
			// 컴퓨터와 유저의 선택을 int형식으로 보관
			int comp = (int)(Math.random()*3)+1;
			System.out.print("철수[가위(1), 바위(2), 보(3), 끝내기(4)] >> ");
			int userp = s.nextInt();
			if (userp == 4) break;
			
			// 각자의 선택을 String으로도 보관
			String comp_str = null;
			String userp_str = null;
			switch (comp) {
				case 1: comp_str = "가위"; break;
				case 2: comp_str = "바위"; break;
				case 3: comp_str = "보"; break;
			}
			switch (userp) {
				case 1: userp_str = "가위"; break;
				case 2: userp_str = "바위"; break;
				case 3: userp_str = "보"; break;
			}
			System.out.println("철수(" + userp_str + ") : "
							 + "컴퓨터(" + comp_str + ")");
			
			  // 유저가 이기는 경우
			if (comp == 1 && userp == 2 
			 || comp == 2 && userp == 3 
			 || comp == 3 && userp == 1) {
				System.out.println("철수가 이겼습니다.");
			} // 컴퓨터가 이기는 경우
			else if (comp == 2 && userp == 1 
				  || comp == 3 && userp == 2 
				  || comp == 1 && userp == 3) {
				System.out.println("컴퓨터가 이겼습니다.");
			} // 비기는 경우
			else
				System.out.println("비겼습니다.");
		}
		s.close();
	}
}

 

 

 

10. 갬블링 게임을 만들어보자.

import java.util.*;


class Person {
	String name;
	int a,b,c;

	public Person(String name) { // 생성자
		this.name = name;
	}
	
	// 랜덤난수 3개 발생 및 할당 메소드
	void valueAssign() { 
		a = (int)(Math.random()*3)+1;
		b = (int)(Math.random()*3)+1;
		c = (int)(Math.random()*3)+1;
	}
	
	// 해당 객체의 차례임을 출력하고, 엔터를 입력하면 난수발생시킨 뒤 출력함.
	void myTurn(Scanner s) { 
		System.out.print("[" + name + "]:<Enter>");
		if (s.nextLine().isEmpty()) {
			this.valueAssign();
			System.out.print("	" + a + "  " + b + "  " + c + "  ");	
		}
	}
	
	// 해당 객체의 차례에서 발생한 난수들이 일치하는지 확인 후 결과 출력
	// boolean을 반환하는 이유는 run()에서 while(true)를 빠져나가기 위함.
	boolean check() { 
		if (this.a == this.b && this.b == this.c) {
			System.out.println(this.name + "님이 이겼습니다!");
			return true;
		}else {
			System.out.println("아쉽군요!");
			return false;
		}
	}
}

public class Main {
	static void run(Scanner s) {
		// 플레이어 두명 이름 입력받고, 객체 생성
		System.out.print("1번째 선수 이름>>");
		Person p1 = new Person(s.nextLine());
		System.out.print("2번째 선수 이름>>");	
		Person p2 = new Person(s.nextLine());
		
		// 누구차례든 a,b,c가 일치하면 break;
		while(true) {
			p1.myTurn(s);
			if (p1.check() == true)
				break;
			
			p2.myTurn(s);
			if (p2.check() == true) 
				break; 
		}
	}
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		run(s);
	}
}

 

 

 

11. StringBuffer클래스를 활용하여 명령처럼 문자열을 수정하라.

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		
		System.out.print(">>");
		StringBuffer sb = new StringBuffer(s.nextLine());
		
		while(true) {
			System.out.print("명령: "); // (str1!str2)로 입력 시 str1을 str2로 변환
			String ord = s.nextLine();
			if (ord.equals("그만"))
				break;
			String temp[] = ord.split("!");
			if (temp.length != 2)
				System.out.println("잘못된 명령입니다!");
			else {// 정상적인 경우
				int idx = sb.indexOf(temp[0]);
				if (idx == -1)
					System.out.println("찾을 수 없습니다!");
				else //정상적인 경우
					sb.replace(idx, idx+temp[0].length(), temp[1]);
			}
			System.out.println(sb);
		}
		System.out.println("종료합니다. . .");
		s.close();
	}
}

 

 

 

12. 문제 10의 갬블링 게임을 n명이 하도록 수정하라.

import java.util.*;


class Person {
	String name;
	int a,b,c;

	public Person(String name) { // 생성자
		this.name = name;
	}
	// 랜덤난수 3개 발생 및 할당 메소드
	void valueAssign() { 
		a = (int)(Math.random()*3)+1;
		b = (int)(Math.random()*3)+1;
		c = (int)(Math.random()*3)+1;
	}
	// 해당 객체의 차례임을 출력하고, 엔터를 입력하면 난수발생시킨 뒤 출력함.
	void myTurn(Scanner s) { 
		System.out.print("[" + name + "]:<Enter>");
		if (s.nextLine().isEmpty()) {
			valueAssign();
			System.out.print("   " + a + "  " + b + "  " + c + "  ");	
		}
	}
	// 해당 객체의 차례에서 발생한 난수들이 일치하는지 확인 후 결과 출력
	// boolean을 반환하는 이유는 run()에서 while(true)를 빠져나가기 위함.
	boolean check() { 
		if (a == b && b == c) {
			System.out.println(name + "님이 이겼습니다!");
			return true;
		}else {
			System.out.println("아쉽군요!");
			return false;
		}
	}
}

public class Main {
	static void run(Scanner s) {
		// 참여인원 입력받고, Person객체 배열 선언
		System.out.print("갬블링 게임에 참여할 선수 숫자>>");
		int num = s.nextInt();
		Person p[] = new Person[num];
		s.nextLine();	// 입력스트림 초기화
		
		// 객체배열 인덱스마다 객체 생성하며 이름을 할당.
		for (int i = 0; i < num; i++) {
			System.out.print(i + "번째 선수 이름>>");
			p[i] = new Person(s.nextLine());
		}
		
		// 누구차례든 a,b,c가 일치하면 break;
		// i%num은 i가 num의 배수가 될때마다 0으로 입력될 수 있게 해줌. 
		// i=0~num까지 i++하는 for문이라고 보면 될듯
		int i =0;
		while (true) {
			p[i%num].myTurn(s);
			if (p[i%num].check() == true) {
				break; }
			i++;
		}
	}
	// 스캐너활성화 및 종료 + run()만 뒀음.
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		run(s);
		s.close();
	}
}