본문으로 바로가기

[Chapter5_실습문제]

category withTextBook/명품 JAVA 프로그래밍 2021. 4. 16. 02:41

   [1~2] 다음 TV 클래스가 있다.

 

1. 다음 main( ) 메소드와 실행 결과를 참고하여 TV를 상속받은 ColorTV 클래스를 작성하라.

 

class TV {
	private int size;
	public TV(int size) { this.size = size; }
	protected int getSize() { return size; }
}


public class ColorTV extends TV {
	
	private int color;
	 
     
	public ColorTV(int size, int color) {
    
		super(size);
		this.color = color;
	}
	
    
	public void printProperty() {
    
		System.out.println(getSize() + "인치 " + color + "컬러");
	}
	
    
	public static void main(String[] args) {
    
		ColorTV myTV = new ColorTV(32, 1024);
		myTV.printProperty();
	}
}

2. 다음 main( ) 메소드와 실행 결과를 참고하여 ColorTV를 상속받는 IPTV 클래스를 작성하라.

 

class TV {

	private int size;
    
    
	public TV(int size) {
    
		this.size = size;
	}
    
    
	protected int getSize() {
    
		return size;
	}
}



public class ColorTV {

	private String addr;
	private int size;
	
    
	public ColorTV (String addr, int size) {
    
		this.addr = addr;
		this.size = size;
	}
	
    
	public String getsAddr() {
    
		return addr;
	}
	
    
	public int getsSize() {
    
		return size;
	}
}



public class IPTV extends ColorTV {
	
	private int color;
	
    
	public IPTV (String addr, int size, int color) {
    
		super(addr, size);
		this.color = color;
	}
	
    
	public void printProperty() {
    
		System.out.println("나의 IPTV는 " + getsAddr() + " 주소의 " + getsSize() + "인치 " + color + "컬러");
	}


	public static void main(String[] args) {
    
		IPTV iptv = new IPTV("192.1.1.2", 32, 2048); // "192.1.1.2" 주소에 32인치, 2048 컬러
		
		iptv.printProperty();
	}
}

[3~4] 다음은 단위를 변환하는 추상 클래스 Converter이다.

 

3. Converter 클래스를 상속받아 원화를 달러로 변환하는 Won2Dollar 클래스를 작성하라.

3. main( ) 메소드와 실행 결과는 다음과 같다.

 

import java.util.Scanner;


abstract class Converter {

	abstract protected double convert(double src); // 추상 메소드
	abstract protected String getSrcString(); // 추상 메소드
	abstract protected String getDestString(); // 추상 메소드
	protected double ratio; // 비율
	
    
	public void run() {
    
		Scanner scanner = new Scanner(System.in);
		System.out.println(getSrcString() + "을 " + getDestString() + "로 바꿉니다.");
		System.out.print(getSrcString() + "을 입력하세요>> ");
		double val = scanner.nextDouble();
		double res = convert(val);
		System.out.println("변환 결과: " + res + getDestString() + "입니다.");
        
		scanner.close();
	}
}



public class Won2Dollar extends Converter {
	
	private Scanner scanner;
	private int won;
	
    
	public Won2Dollar (int won) {
    
		this.won = won;
		scanner = new Scanner(System.in);
	}


	public String getSrcString() {
    
		return "원";
	}
	
    
	public String getDestString() {
    
		return "달러";
	}
	
    
	public double convert(double src) {
    
		return src / 1200;
	}
	
    
	public static void main(String[] args) {
    
		Won2Dollar toDollar = new Won2Dollar(1200); // 1달러는 1200원
        
		toDollar.run();
	}
}

4. Converter 클래스를 상속받아 Km를 mile(마일)로 변환하는 Km2Mile 클래스를 작성하라.

4. main( ) 메소드와 실행 결과는 다음과 같다.

 

import java.util.Scanner;

abstract class Converter {

	abstract protected double convert(double src); // 추상 메소드
	abstract protected String getSrcString(); // 추상 메소드
	abstract protected String getDestString(); // 추상 메소드
	protected double ratio; // 비율
	
    
	public void run() {
    
		Scanner scanner = new Scanner(System.in);
		System.out.println(getSrcString() + "을 " + getDestString() + "로 바꿉니다.");
		System.out.print(getSrcString() + "을 입력하세요>> ");
		double val = scanner.nextDouble();
		double res = convert(val);
		System.out.println("변환 결과: " + res + getDestString() + "입니다.");
        
		scanner.close();
	}
}



public class Km2Mile extends Converter {
	
	int mile;
	double km;
	
    
	public Km2Mile (int mile, double km) {
    
		this.mile = mile;
		this.km = km;
	}
	
    
	public String getSrcString() {
    
		return "Km";
	}
	
    
	public String getDestString() {
    
		return "mile";
	}
	
    
	public double convert (double src) {
    
		return src / 1.6;
	}


	public static void main(String[] args) {
    
		Km2Mile toMile = new Km2Mile(1, 6); // 1마일은 1.6Km
        
		toMile.run();
	}
}

[5~8] 다음은 2차원 상의 한 점을 표현하는 Point 클래스이다.

 

5. Point를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라.

5. 다음 main( ) 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

 

public class Point {

	private int x, y;
	
    
	public Point (int x, int y) { this.x = x; this.y = y;}
	
    
	public int getX() { return x; }
	public int getY() { return y; }
	
    
	protected void move (int x, int y) { this.x = x; this.y = y; }
}



public class ColorPoint extends Point {
	
	private String color;
	
    
	public ColorPoint (int x, int y, String color) {
    
		super(x, y);
		this.color = color;
	}
	
    
	public void setXY (int x, int y) {
    
		move(x, y);
	}
	
    
	public void setColor (String color) {
    
		this.color = color;
	}
	
    
	public String toString() {
    
		return (color + "색의 (" + getX() + "," + getY() + ")의 점");
	}


	public static void main(String[] args) {
    
		ColorPoint cp = new ColorPoint(5, 5, "YELLOW");
		cp.setXY(10, 20);
		cp.setColor("RED");
        
		String str = cp.toString();
		System.out.println(str + "입니다.");
	}
}

6. Point를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라.

6. 다음 main( ) 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

 

public class Point {

	private int x, y;
	
    
	public Point(int x, int y) { this.x = x; this.y = y;}
	
    
	public int getX() { return x; }
	public int getY() { return y; }
	
    
	protected void move(int x, int y) { this.x = x; this.y = y; }
}



public class ColorPoint extends Point {
	
	private String color;
	
	public ColorPoint() {
    
		super(0,0);
		color = "BLACK";
	}
    
    
	public ColorPoint (int x, int y) {
    
		super(x, y);
		color = "BLACK";
	}
	
    
	public void setXY (int x, int y) {
    
		move(x, y);
	}
	
    
	public void setColor (String color) {
    
		this.color = color;
	}
	
    
	public String toString() {
    
		return (color + "색의 (" + getX() + "," + getY() + ")의 점");
	}


	public static void main(String[] args) {
    
		ColorPoint zeroPoint = new ColorPoint();
        
		System.out.println(zeroPoint.toString() + "입니다.");
		
        
		ColorPoint cp = new ColorPoint(10, 10);
        
		cp.setXY(5, 5);
		cp.setColor("RED");
        
		System.out.println(cp.toString() + "입니다.");
	}
}

7. Point를 상속받아 3차원의 점을 나타내는 Point3D 클래스를 작성하라.

7. 다음 main( ) 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

 

public class Point {

	private int x, y;
    
    
	public Point(int x, int y) { this.x = x; this.y = y;}
    
    
	public int getX() { return x; }
	public int getY() { return y; }
    
    
	protected void move(int x, int y) { this.x = x; this.y = y; }
}



public class Point3D extends Point {
	
	private int z;
	
    
	public Point3D (int x, int y, int z) {
    
		super(x, y);
		this.z = z;
	}
	
    
	public void move (int x, int y, int z) {
    
		move(x, y);
		this.z = z;
	}
	
    
	public void moveUp() {
    
		this.z += 1;
	}
	
    
	public void moveDown() {
    
		this.z -= 1;
	}
	
    
	public String toString() {
    
		return "(" + getX() + "," + getY() + "," + z + ")의 점";
	}


	public static void main(String[] args) {
    
		Point3D p = new Point3D(1, 2, 3); // 1, 2, 3은 각각 x, y, z축의 값
		System.out.println(p.toString() + "입니다.");
		
		p.moveUp(); // z 축으로 위쪽 이동
		System.out.println(p.toString() + "입니다.");
		
		p.moveDown(); // z 축으로 아래쪽 이동
		p.move(10, 10); // x, y 축으로 이동
		System.out.println(p.toString() + "입니다.");
		
		p.move(100, 200, 300); // x, y, z 축으로 이동
		System.out.println(p.toString() + "입니다.");
	}
}

8. Point를 상속받아 양수의 공간에서만 점을 나타내는 PositivePoint 클래스를 작성하라.

8. 다음 main( ) 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

 

public class PositivePoint extends Point {
	
	public PositivePoint() {
		super(0,0);
	}
    
    
	public PositivePoint (int x, int y) {
    
		super(x, y);
        
		if (x < 0 || y < 0) {
			super.move(0,0);
		}
	}
	
    
	public void move (int x, int y) {
    
		if (x >= 0 && y >= 0)
			super.move(x, y);
	}
	
    
	public String toString() {
    
		return "(" + getX() + "," + getY() + ")의 점";
	}


	public static void main(String[] args) {
    
		PositivePoint p = new PositivePoint();
		p.move(10, 10);
		System.out.println(p.toString() + "입니다.");
		
        
		p.move(-5, 5); // 객체 p는 음수 공간으로 이동되지 않음
		System.out.println(p.toString() + "입니다.");
		
        
		PositivePoint p2 = new PositivePoint(-10, -10);
		System.out.println(p2.toString() + "입니다.");
	}
}

9. 다음 Stack 인터페이스를 상속받아 실수를 저장하는 StringStack 클래스를 구현하라.

9. 그리고 다음 실행 사례와 같이 작동하도록 StackApp 클래스에 main( ) 메소드를 작성하라.

 

import java.util.Scanner;

public interface Stack {

	int length(); // 현재 스택에 저장된 개수 리턴
	int capacity(); // 스택의 전체 저장 가능한 개수 리턴
	String pop(); // 스택의 톱(top)에 실수 저장
	boolean push(String val); // 스택의 톱(top)에 저장된 실수 리턴
}



public class StringStack implements Stack {

	private int size;
	private String[] stack;
	private int top;
	
    
	StringStack (int size) {
    
		this.size = size;
		stack = new String[size];
		top = -1;
	}
	
    
	public int length() { // 현재 스택에 저장된 개수 리턴
    
		return top + 1;
	}
	
    
	public int capacity() { // 스택에 전체 저장 가능한 개수 리턴
    
		return size - top + 1;
	}
	
    
	public String pop() { // 스택의 top에 문자열 저장 
		
		return stack[top--];
	}
	
    
	public boolean push (String val) { // 스택의 top에 저장된 문자열 리턴
    
		if (top+1 < size) {
			stack[++top] = val;
			return true;
		}
		else
			return false;
	}
}



public class StackApp {
	
	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("총 스택 저장 공간의 크기 입력 >> ");
		int size = scanner.nextInt();
		StringStack stack = new StringStack(size);
		
        
		while (true) {
			System.out.print("문자열 입력 >> ");
			String str = scanner.next();
			
			if (str.equals("그만"))
				break;
			
			if (!stack.push(str))
				System.out.println("스택이 꽉 차서 푸시 불가!");
		}
		
        
		System.out.print("스택에 저장된 모든 문자열 팝 : ");
        
		while (stack.length() > 0) {
        
			System.out.print(stack.pop() + " ");
		}
		
        
		scanner.close();
	}
}

10. 다음은 키와 값을 하나의 아이템으로 저장하고 검색 수정이 가능한 추상 클래스가 있다.

10. PairMap을 상속받는 Dictionary 클래스를 구현하고,

10. 이를 다음과 같이 활용하는 main( ) 메소드를 가진 클래스 DictionaryApp도 작성하라.

 

abstract class PairMap {

	protected String keyArray []; // key 들을 저장하는 배열
	protected String valueArray []; // value 들을 저장하는 배열
    
	abstract String get(String key); // key 값을 가진 value 리턴. 없으면 null 리턴
    
	abstract void put(String key, String value); // key와 value를 쌍으로 저장. 기존에 key가 있으면, 값을 value로 수정
	
	abstract String delete(String key); // key 값을 가진 아이템(value와 함께) 삭제. 삭제된 value 값 리턴
	
	abstract int length(); // 현재 저장된 아이템의 개수 리턴
}



public class Dictionary extends PairMap {
	
	private int size;
	private String keyArray [];
	private String valueArray [];
	
    
	public Dictionary (int size) {
    
		this.size = size;
		keyArray = new String[size];
		valueArray = new String[size];
	}
	
    
	public String get (String key) {
    
		for (int i = 0; i < length(); i++) {
			if (key.equals(keyArray[i]))
				return valueArray[i];
		}
        
		return null;
	}
	
    
	public void put (String key, String value) {
    
		boolean check = false;
		
		for (int i = 0; i < length(); i++) {
			if (keyArray[i].equals(key)) {
				valueArray[i] = value;
				check = true;
			}
		}
		
		
        if (check == false && length() < size) {
			int index = length();
            
			keyArray[index] = key;
			valueArray[index] = value;
		}
	}
	
    
	public String delete (String key) {
    
		for (int i = 0; i < keyArray.length; i++) {
			if (key.equals(keyArray[i])) {
				String value = valueArray[i];
				valueArray[i] = null;
				keyArray[i] = null;
                
				return value;
			}
		}
        
		return "삭제할 값이 존재하지 않습니다.";
	}
	
    
	public int length() {
    
		int num = 0;
		for (int i = 0; i < keyArray.length; i++) {
			if (keyArray[i] != null)
				num++;
			else
				break;
		}
		
		return num;
	}
}



public class DictionaryApp {

	public static void main(String[] args) {
    
		Dictionary dic = new Dictionary(10);
		dic.put("황기태", "자바");		
		dic.put("이재문", "파이썬");
		dic.put("이재문", "C++"); // 이재문의 값을 C++로 수정
		
		System.out.println("이재문의 값은 " + dic.get("이재문"));
		System.out.println("황기태의 값은 " + dic.get("황기태"));

		dic.delete("황기태"); // 황기태 아이템 삭제
		System.out.println("황기태의 값은 " + dic.get("황기태")); // 삭제된 아이템 접근
	}
}

11. 철수 학생은 다음 3개의 필드와 메소드를 가진 4개의 클래스 Add, Sub, Mul, Div를 작성하려고 한다(4장 실습문제 11 참고).

  • int 타입의 a, b 필드: 2개의 피연산자
  • void setvalue(int a, int b): 피연산자 값을 객체 내에 저장한다.
  • int calculate( ): 클래스의 목적에 맞는 연산을 실행하고 결과를 리턴한다.

11. 곰곰히 생각해보니, Add, Sub, Mul, Div 클래스에 공통된 필드와 메소드가 존재하므로

11. 새로운 추상 클래스 Calc를 작성하고 Calc를 상속받아 만들면 되겠다고 생각했다.

11. 그리고 main( ) 메소드에서 다음 실행 사례와 같이 2개의 정수와 연산자를 입력받은 후,

11. Add, Sub, Mul, Div 중에서 이 연산을 처리할 수 있는 객체를 생성하고

11. setValue( )와 calculate( )를 호출하여 그 결과 값을 화면에 출력하면 된다고 생각하였다.

11. 철수처럼 프로그램을 작성하라.

 

import java.util.Scanner;

abstract class Calc {

	abstract public void setValue(int a, int b);
    
	abstract public int calculate();
}



public class Add extends Calc {

	private int a;
	private int b;
	
    
	public void setValue (int a, int b) {
    
		this.a = a;
		this.b = b;
	}
	
    
	public int calculate() {
    
		return a + b;
	}
}



public class Sub extends Calc {

	private int a;
	private int b;
	
    
	public void setValue (int a, int b) {
    
		this.a = a;
		this.b = b;
	}
	
    
	public int calculate() {
		return a - b;
	}
}



public class Mul extends Calc {

	private int a;
	private int b;
	
    
	public void setValue (int a, int b) {
    
		this.a = a;
		this.b = b;
	}
	
    
	public int calculate() {
    
		return a * b;
	}
}



public class Div extends Calc {

	private int a;
	private int b;
	
    
	public void setValue (int a, int b) {
    
		this.a = a;
		this.b = b;
	}
	
    
	public int calculate() {
    
		return a / b;
	}
}



public class CalcApp {

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
        
		System.out.print("두 정수와 연산자를 입력하시오>>");
		int a = scanner.nextInt();
		int b = scanner.nextInt();
		char op = scanner.next().charAt(0);
		
        
		switch (op) {
			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;
		}
		
        
		scanner.close();
	}
}

12. 텍스트로 입출력하는 간단한 그래픽 편집기를 만들어보자.

12. 본문 5.6절과 5.7절에서 사례로 든 추상 클래스 Shape과 Line, Rect, Circle 클래스 코드를 잘 완성하고 이를 활용하여

12. 아래 실행 예시처럼 "삽입", "삭제", "모두 보기", "종료"의 4가지 그래픽 편집 기능을 가진 클래스 GraphicEditor을 작성하라.

 

 


13. 다음은 도형의 구성을 묘사하는 인터페이스이다.

13. 다음 main( ) 메소드와 실행 결과를 참고하여, 인터페이스 Shape을 구현한 클래스 Circle를 작성하고 전체 프로그램을 완성하라.

 

interface Shape {

	final double PI = 3.14; // 상수
    
    
	void draw(); // 도형을 그리는 추상 메소드 
	double getArea(); // 도형의 면적을 리턴하는 추상 메소드
    
    
	default public void redraw() { // default 메소드
    
		System.out.print("--- 다시 그립니다. ");
		draw();
	}
}



public class Circle implements Shape {
	
	private int radius;
	
    
	public Circle (int radius) {
    
		this.radius = radius;
	}
	
    
	public void draw() {
    
		System.out.println("반지름이 " + radius + "인 원입니다.");
	}
	
	
	public double getArea() {
    
		return PI * radius * radius;
	}


	public static void main(String[] args) {
    
		Shape donut = new Circle(10); // 반지름이 10인 원 객체
        
		donut.redraw();
        
		System.out.println("면적은 " + donut.getArea());
	}
}

14. 다음 main( ) 메소드와 실행 결과를 참고하여, 문제 13의 Shape 인터페이스를 구현한 클래스 Oval, Rect를 추가 작성하고

14. 전체 프로그램을 완성하라.

 

interface Shape {

	final double PI = 3.14; // 상수
    
    
	void draw(); // 도형을 그리는 추상 메소드
	double getArea(); // 도형의 면적을 리턴하는 추상 메소드
    
    
	default public void redraw() { // default 메소드
    
		System.out.print("--- 다시 그립니다. ");
		draw();
	}
}



public class Circle implements Shape {
	
	private int radius;
	
    
	public Circle (int radius) {
    
		this.radius = radius;
	}
	
    
	public void draw() {
    
		System.out.println("반지름이 " + radius + "인 원입니다.");
	}
	
	
	public double getArea() {
    
		return PI * radius * radius;
	}


	public static void main(String[] args) {
    
		Shape donut = new Circle(10); // 반지름이 10인 원 객체
        
		donut.redraw();
		System.out.println("면적은 " + donut.getArea());
	}
}



public class Oval implements Shape {

	private int x, y;
	
    
	public Oval (int x, int y) {
    
		this.x = x;
		this.y = y;
	}
	
    
	public void draw() {
    
		System.out.println(x + "x" + y + "에 내접하는 타원입니다.");
	}
	
    
	public double getArea() {
    
		return PI * x * y;
	}
}



public class Rect implements Shape {

	private int x, y;
	
    
	public Rect (int x, int y) {
    
		this.x = x;
		this.y = y;
	}
	
    
	public void draw() {
    
		System.out.println(x + "x" + y + "크기의 사각형 입니다.");
	}
	
    
	public double getArea() {
    
		return x * y;
	}
}



public class ShapeApp {

	public static void main(String[] args) {
    
		Shape [] list = new Shape[3]; // Shape을 상속받은 클래스 객체의 레퍼런스 배열
        
		list[0] = new Circle(10); // 반지름이 10인 원 객체
		list[1] = new Oval(20, 30); // 20x30 사각형에 내접하는 타
		list[2] = new Rect(10, 40); // 10x40 크기의 사각형
		
        
		for (int i = 0; i < list.length; i++)
			list[i].redraw();
            
            
		for (int i = 0; i < list.length; i++)
			System.out.println("면적은 " + list[i].getArea());
	}
}