M

5장 실습문제 본문

Java/명품 Java Programming

5장 실습문제

M_master 2022. 2. 23. 00:24
class TV {
	private int size;
    public TV(int size) { this.size = size; }
    protected int getSize() { return size; }
}

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

public static void main(String[] args) {
	ColorTV myTV = new ColorTV(32, 1024);
    myTV.printProperty();
}

풀이

class ColorTV extends TV {
	private int resolution;
	
	public ColorTV(int size, int resolution) {
		super(size);
		this.resolution = resolution;
	}
	
	public void printProperty() {
		System.out.println(getSize() +"인치 "+ resolution +"컬러");
	}
}

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

public static void main(String[] args) {
	IPTV iptv = new IPTV("192.1.1.2", 32, 1024);
    iptv.printProperty();
}

풀이

class IPTV extends ColorTV {
	private String ip;
	
	public IPTV(String ip, int size, int resolution) {
		super(size, resolution);
		this.ip = ip;
	}
	
	public void printProperty() {
		System.out.print("나의 IPTV는 "+ ip +" 주소의 ");
		super.printProperty();
	}
}

 

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

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

3. Converter 클래스를 상속받아 원화를 달러로 변환하는 Won2Dollar 클래스를 작성하라. main() 메소드와 실행 결과는 다음과 같다.

public static void main(String args[]) {
	Won2Dollar toDollar = new Won2Dollar(1200); // 1달러는 1200원
    toDollar.run();
}

풀이

class Won2Dollar extends Converter {
	public Won2Dollar(int ratio) {
		this.ratio = ratio;
	}
	
	protected double convert(double src) { return src / ratio; }
	protected String getSrcString() { return "원"; }
	protected String getDestString() { return "달러"; }
}

4. Converter 클래스를 상속받아 Km를 mile(마일)로 변환하는 km2Mile 클래스를 작성하라. main() 메소드와 실행 결과는 다음과 같다.

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

풀이

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

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

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

5. Point를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

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 + "입니다.");
 }

풀이

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) { super.move(x,  y); }
	public void setColor(String color) { this.color = color; }
	
	public String toString() {
		return color +"색의 ("+ getX() +", "+ getY() +")의 점";
	}
}

6. Point를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

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

풀이

class ColorPoint extends Point {
	private String color;
	
	ColorPoint() {
		super(0, 0);
		this.color = "BLACK"; 
	}
	
	ColorPoint(int x, int y) {
		super(x, y);
        this.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() + ")의 점";
	}
}

7. Point를 상속받아 3차원의 점을 나타내는 Point3D 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

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() + "입니다.");
}

풀이

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

8. Point를 상속받아 양수의 공간에서만 점을 나타내는 PositivePoint 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

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() + "입니다.");
}

풀이

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

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

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

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

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

class StringStack implements Stack {
	String[] stackArr;
	private int saveLen, index;
		
	StringStack(int len) {
		this.saveLen = len;
		int index = 0;
		stackArr = new String[len];
	}
	
	public int length() { return index; }
	public int capacity() { return saveLen; }
	public String pop() { return this.stackArr[--index]; }
	
	public boolean push(String val) {
		if(saveLen <= index) {
			System.out.println("스택이 꽉 차서 푸시 불가!");
			return false; 
		}
		
		stackArr[index] = val;
		index++;
		return true;
	}
}

public class StackApp {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		StringStack stringStack;
		
		System.out.print("총 스택 저장 공간의 크기 입력 >> ");
		int stackSize = sc.nextInt();
		
		stringStack = new StringStack(stackSize);
		
		
		while(true) {
			System.out.print("문자열 입력 >> ");
			String s = sc.next();
			
			if(s.equals("그만")) break;
			
			stringStack.push(s);
		}
		
		System.out.print("스택에 저장된 모든 문자열 팝 :");
		int len = stringStack.length();
		for(int i = 0; i < len; i++ ) {
			System.out.print(" "+ stringStack.pop());
		}
		
		sc.close();
	}

}

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

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

PairMap을 상속받는 Dictionary 클래스를 구현하고, 이를 다음과 같이 활용하는 main() 메소드를 가진 클래스 DictionaryApp도 작성하라.

abstract class PairMap {
    protected String keyArray[];
    protected String valueArray[];
    abstract String get(String key);
    abstract void put(String key, String value);
    abstract String delete(String key);
    abstract int length();
}

class Dictionary extends PairMap {
	private int index;
		
	Dictionary(int n) {
		keyArray = new String[n];
		valueArray = new String[n];
		this.index = 0;
	}
	
	public String get(String key) {
		for(int i = 0; i < keyArray.length; i++) {
			if(key.equals(keyArray[i])) {
				return valueArray[i];
			}
		}
		return null;
	}
	
	@Override
	public void put(String key, String value) {
		for(int i = 0; i < index; i++) {
			if(keyArray[i].equals(key)) {
				valueArray[i] = value;
				return;
			}
		}
		
		keyArray[index] = key;
		valueArray[index] = value;
		index++;
	}
	
	@Override
	public String delete(String key) {
		for(int i = 0; i < index; i++) {
			if(key.equals(keyArray[i])) {
				String keyName = keyArray[i];
				keyArray[i] = null;
				valueArray[i] = null;
				return keyName;
			}
		}
		return null;
	}
	
	@Override
	public int length() { return index; }
}

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

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

곰곰 생각해보니, Add, Sub, Mul, Div 클래스에 공통된 필드와 메소드가 존재하므로 새로운 추상 클래스 Calc를 작성하고 Calc를 상속받아 만들면 되겠다고 생각했다. 그리고 main() 메소드에서 다음 실행 사례와 같이 2개의 정수와 연산자를 입력받은 후 Add, Sub, Mul, Div 중에서 이 연산을 처리할 수 있는 객체를 생성하고 setValue()와 calculate()를 호출하여 그 결과 값을 화면에 출력하면 된다고 생각하였다. 철수처럼 프로그램을 작성하라.

abstract class Calc {
	protected int a;
	protected int b;
	public void setValue(int a, int b) {
		this.a = a;
		this.b = b;
	}
	abstract int calculate();
}

class Add extends Calc {
	public int calculate() { return a + b; }
}

class Sub extends Calc {
	public int calculate() { return a - b; }
}

class Mul extends Calc {
	public int calculate() { return a * b; }
}

class Div extends Calc {
	public int calculate() {
		if(b <= 0) return -1;
		
		return a / b; 
	}
}

public class Calculator {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Calc calc;
		int result = 0;
		
		System.out.print("두 정수와 연산자를 입력하시오>>");
		int a = sc.nextInt(); 
		int b = sc.nextInt();
		String type = sc.next();
		
		switch(type) {
			case "+": calc = new Add(); break;
			case "-": calc = new Sub(); break;
			case "*": calc = new Mul(); break;
			case "/": calc = new Div(); break;
			default:
				System.out.println("올바른 연산자를 입력해주세요.");
				sc.close();
				return;
		}
		
		calc.setValue(a, b);
		result = calc.calculate();
		System.out.println(result);
		sc.close();
	}

}

12. 텍스트로 입출력하는 간단한 그래픽 편집기를 만들어보자. 본문 5.6절과 5.7절에서 사례로 든 추상 클래스 Shape과 Line, Rect, Circle 클래스 코드를 잘 완성하고 이를 활용하여 아래 시행 예시처럼 "삽입", "삭제", "모두 보기", "종료"의 4가지 그래픽 편집 기능을 가진 클래스 GraphicEditor을 작성하라.

abstract class Shape {
   private Shape next;
   public Shape() { next = null; }
   public void setNext(Shape obj) { next = obj; } // 링크 연결
   public Shape getNext() { return next; }
   public abstract void draw();
}

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

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

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

public class GraphicEditor {
	Shape head, tail;
	Scanner sc;
	
	GraphicEditor() {
		head = null;
		tail = null;
	}
	
	public void insert(int num) {
		Shape s = null;
		
		switch(num) {
			case 1:
				s = new Line();
				break;
			case 2:
				s = new Rect();
				break;
			case 3:
				s = new Circle();
				break;
		}
		
		if(head == null) {
			head = s;
			tail = s;
		} else {
			tail.setNext(s);
			tail = s;
		}
	}
	
	public void delete(int n) {
		int i;
		Shape cu = head;
		Shape temp = head;;
		
		if(n == 1) {
			if(head == tail) {
				head = null;
				tail = null;
				return;
			} else {
				head = head.getNext();
				return;
			}
		}
		
		for(i = 1; i < n; i++) {
			temp = cu;
			cu = cu.getNext();
			if(cu == null) { // 노드 수가 입력 값보다 적을때
	            System.out.println("삭제할 수 없습니다.");
	            return;
	         }
		}
		
		if(i == n) {
			temp.setNext(cu.getNext());
			tail = temp;
		} else {
	         temp.setNext(cu.getNext());
		}
	}
	
	public void print() {
		Shape s = head;
		while(s != null) {
			s.draw();
			s = s.getNext();
		}
	}
	
	public void run() {
		sc = new Scanner(System.in);
		
		System.out.println("그래픽 에디터 beauty을 실행합니다.");
		
		while(true) {
			System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>");
			int n = sc.nextInt();
			
			switch(n) {
				case 1:
					System.out.print("Line(1), Rect(2), Circle(3)>>");
					n = sc.nextInt(); 
					insert(n);
					break;
					
				case 2:
					System.out.print("삭제할 도형의 위치>>");
					n = sc.nextInt();
					delete(n);
					break;
				case 3:
					print();
					break;
					
				case 4:
					System.out.println("beauty을 종료합니다.");
					sc.close();
					return;
			}
		}
	}
	
	public static void main(String[] args) {
		GraphicEditor graphicEditor = new GraphicEditor();
		graphicEditor.run();
	}

}

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

interface Shape {
    final double PI = 3.14;
    void draw();
    double getArea();
    default public void redraw() {
    	System.out.println("--- 다시 그립니다.");
        draw();
     }
}

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

public static void main(String[] args) {
    Shape donut = new Circle(10);
    donut.redraw();
    System.out.println("면적은 " + donut.getArea());
}

풀이

interface Shape {
    final double PI = 3.14;
    void draw();
    double getArea();
    default public void redraw() {
    	System.out.print("--- 다시 그립니다.");
        draw();
     }
}

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

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

public static void main(String[] args) {
    Shape[] list = new Shape[3];
    list[0] = new Circle(10);
    list[1] = new Oval(20, 30);
    list[2] = new Rect(10, 40);

    for(int i = 0; i < list.length; i++) list[1].redraw();
    for(int i = 0; i < list.length; i++) System.out.println("면적은 "+ list[i].getArea());
}

풀이

interface Shape {
    final double PI = 3.14;
    void draw();
    double getArea();
    default public void redraw() {
    	System.out.print("--- 다시 그립니다.");
        draw();
     }
}

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

class Oval implements Shape {
	private int a, b;
	Oval(int a, int b) {
		this.a = a;
		this.b = b;
	}
	
	public void draw() {
		System.out.printf("%dx%d에 내접하는 타원입니다.\n", this.a, this.b);
	}
	
	public double getArea() {
		return PI * this.a * this.b;
	}
}

class Rect implements Shape {
	private int a, b;
	Rect(int a, int b) {
		this.a = a;
		this.b = b;
	}
	
	public void draw() {
		System.out.printf("%dx%d크기의 사격형 입니다.\n", this.a, this.b);
	}
	
	public double getArea() {
		return this.a * this.b;
	}
}
728x90

'Java > 명품 Java Programming' 카테고리의 다른 글

5장 연습문제  (0) 2022.02.20
5장 Open Challenge  (0) 2022.02.18
4장 실습문제  (0) 2022.02.07
4장 연습문제  (0) 2022.02.07
4장 Open Challenge  (0) 2022.02.06