JAVA/명품 JAVA Programming

[(개정판 4판) 명품 JAVA Programming] 5장 실습 문제

최옥구 2023. 1. 31. 23:00
반응형

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

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

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(super.getSize() + "인치 " + color + "컬러");
	}
	public static void main(String[] args) {
		ColorTV myTV = new ColorTV(32, 1024);
		myTV.printProperty();
	}
}

 


 

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

[결과]

[소스 코드]

class TV{
	private int size;
	public TV(int size) {this.size = size;}
	protected int getSize() {return size;}
}
class ColorTV extends TV{
	private int color;
	public ColorTV(int size, int color){
		super(size);
		this.color = color;
	}
	public void printProperty() {
		System.out.println(super.getSize() + "인치 " + color + "컬러");
	}
}
public class IPTV extends ColorTV{
	private String address;
	public IPTV(String address, int size, int color) {
		super(size, color);
		this.address = address;
	}
	public void printProperty() {
		System.out.print("나의 IPTV는 " + address + " 주소의 ");
		super.printProperty();
	}
	public static void main(String[] args) {
		IPTV iptv = new IPTV("192.1.1.2", 32, 2048);
		iptv.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 클래스를 상속받아 원화를 달러로 변환하는 Won2Dollor 크래스를 작성하라. main() 메소드와 실행 결과는 다음과 같다.  // 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 Won2Dollor extends Converter{
	private int oneDollor;
	public Won2Dollor(int oneDollor) { 
		this.oneDollor = oneDollor;
	}
	protected double convert(double src) {return src / oneDollor;}
	protected String getSrcString() {return "원";}
	protected String getDestString() {return "달러";}
	
	public static void main(String[] args) {
		Won2Dollor toDollor = new Won2Dollor(1200);
		toDollor.run();
	}
}

 


 

4. Converter 클래스를 상속받아 Km를 mile(마일)로 변환하는 Km2Mile 클래스를 작성하라. main() 메소드와 실행 결과는 다음과 같다. // 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{
	private double oneMile;
	public Km2Mile(double oneMile) { 
		this.oneMile = oneMile;
	}
	protected double convert(double src) {return src / oneMile;}
	protected String getSrcString() {return "Km";}
	protected String getDestString() {return "Mile";}
	
	public static void main(String[] args) {
		Km2Mile toDollor = new Km2Mile(1.6);
		toDollor.run();
	}
}

 


 

[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 main(int x, int y) {this.x = x; this.y = y;}
}

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

[결과]

[소스 코드]

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 main(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) {
		main(x, y);
	}
	public void setColor(String color) {
		this.color = color;
	}
	public String toString() {
		return color + "색의 (" + super.getX() + ", " + super.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 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

[결과]

[소스 코드]

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 main(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);
	}
	public void setXY(int x, int y) {
		main(x, y);
	}
	public void setColor(String color) {
		this.color = color;
	}
	public String toString() {
		return color + "색의 (" + super.getX() + ", " + super.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 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

[결과]

[소스 코드]

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 main(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 moveUp() {
		this.z++;
	}
	public void moveDown() {
		this.z--;
	}
	public void move(int x, int y) {
		main(x, y);
	}
	public void move(int x, int y, int z) {
		main(x, y);
		this.z = z;
	}
	public String toString() {
		return "(" + super.getX() + ", " + super.getY() + ", " + this.z +")의 점";
	}
	public static void main(String[] args) {
		Point3D p = new Point3D(1, 2, 3);
		System.out.println(p.toString() + "입니다.");
		
		p.moveUp();
		System.out.println(p.toString() + "입니다.");
		p.moveDown();
		p.move(10, 10);
		System.out.println(p.toString() + "입니다.");
		
		p.move(100, 200, 300);
		System.out.println(p.toString() + "입니다.");
	}
}

 


 

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

[결과]

[소스 코드]

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 main(int x, int y) {this.x = x; this.y = y;}
}
public class PositivePoint extends Point{
	public PositivePoint() {
		super(0, 0);
	}
	public void move(int x, int y) {
		if(x >= 0 && y >= 0)
			main(x, y);
	}
	public String toString() {
		return "(" + super.getX() + ", " + super.getY() + ")의 점";
	}
	public static void main(String[] args) {
		PositivePoint p = new PositivePoint();
		p.move(10, 10);
		System.out.println(p.toString() + "입니다.");
		
		p.move(-5, 5);
		System.out.println(p.toString() + "입니다.");
		
		PositivePoint p2 = new PositivePoint();
		System.out.println(p2.toString() + "입니다.");
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;

interface Stack{
	int length();
	int capacity();
	String pop();
	boolean push(String val);
}
class StringStack implements Stack{
	private int i = -1, length = 0, capacity;
	private String []Array;
	public StringStack() {
		System.out.print("총 스택 저장 공간의 크기 입력 >> ");
		Scanner scanner = new Scanner(System.in);
		this.capacity = scanner.nextInt();
		Array = new String[capacity];
	}
	public int length() {
		return length;
	}
	public int capacity() {
		return capacity;
	}
	public String pop() {
		i++;
		return Array[i];
	}
	public boolean push(String val) {
		if (length >= capacity) return true;
		else {
			Array[length] = val;
			length++;
			return false;
		}				
	}
}
public class StackApp{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		StringStack ss = new StringStack();
		while(true) {
			System.out.print("문자열 입력 >> ");
			String str = scanner.nextLine();
			if(str.equals("그만")) break;
			else if(ss.push(str)) {
				System.out.println("스택이 꽉 차서 푸시 불가.");
				continue;
			}
		}
		System.out.print("스택에 저장된 모든 문자열 팝 : ");
		for(int i = 0; i < ss.capacity(); i++) {
			System.out.print(ss.pop() + " ");
		}
		scanner.close();
	}
}

 


 

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

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

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

[결과]

[소스 코드]

abstract class PairMap{
	protected String keyArray[];
	protected String valueArray[];
	abstract String get(String key);
	abstract String delete(String key);
	abstract int length();
}
class Dictionary extends PairMap{
	private int size;
	private int pos = 0;
	
	public Dictionary() {}
	public Dictionary(int size) {
		this.size = size;
		keyArray = new String[size];
		valueArray = new String[size];
	}
	public void put(String name, String cLanguage) {
		boolean checking = true;
		if(pos != 0) {
			for(int i = 0; i < pos; i++) {
				if(keyArray[i].equals(name)) {
					valueArray[i] = cLanguage;
					checking = false;
					break;
				}
			}
		}
		if(checking) {
			keyArray[pos] = name;
			valueArray[pos] = cLanguage;
			pos++;
		}
	}
	public String get(String key) {
		for(int i = 0; i < size; i++) {
			if(keyArray[i].equals(key))
				return valueArray[i];
		}
		return "해당 사항  없음";		
	}
	public String delete(String key) {
		for(int i = 0; i < size; i++) {
			if(keyArray[i].equals(key))
				return valueArray[i] = null;
		}
		return "해당 사항 없음";
	}
	public int length() {
		return pos;
	}
}
public class DictionaryApp extends Dictionary{
	public static void main(String[] args) {
		Dictionary dic = new Dictionary(10);
		dic.put("황기태", "자바");
		dic.put("이재문", "파이썬");
		dic.put("이재문", "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(): 클래스의 목적에 맞는 연산을 실행하고 결과를 리턴한다.

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

[결과]

[소스 코드]

import java.util.Scanner;

abstract class Calc{
	protected int a;
	protected int b;
	abstract void setValue(int a, int b);
	abstract int calculate();
}
class Add extends Calc{
	public void setValue(int a, int b) {
		super.a = a;
		super.b = b;
	}
	public int calculate() {
		return a + b;
	}
}
class Sub extends Calc{
	public void setValue(int a, int b) {
		super.a = a;
		super.b = b;
	}
	public int calculate() {
		return a - b;
	}
}
class Mul extends Calc{
	public void setValue(int a, int b) {
		super.a = a;
		super.b = b;
	}
	public int calculate() {
		return a * b;
	}
}
class Div extends Calc{
	public void setValue(int a, int b) {
		super.a = a;
		super.b = b;
	}
	public int calculate() {
		return a / b;
	}
}
public class Calculator{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.print("두 정수와 연산자를 입력하세요 >> ");
		int a = scanner.nextInt();
		int b = scanner.nextInt();
		String op = scanner.next();
		switch(op) {
		case "+":
			Add add = new Add();
			add.setValue(a, b);
			System.out.print(add.calculate());
			break;
		case "-":
			Sub sub = new Sub();
			sub.setValue(a, b);
			System.out.print(sub.calculate());
			break;
		case "*":
			Mul mul = new Mul();
			mul.setValue(a, b);
			System.out.print(mul.calculate());
			break;
		case "/":
			Div div = new Div();
			div.setValue(a, b);
			System.out.print(div.calculate());
			break;
		}
		scanner.close();
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;
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");
    }
}

class GraphicEditor{
    private Shape head, tail;
    private Scanner scanner = new Scanner(System.in);
    public void run(){
        System.out.println("그래픽 에디터 beauty를 실행합니다.");
        while(true){
            System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4)>> ");
            int input = scanner.nextInt();
            if(input == 4) {
            	System.out.println("beauty를 종료합니다.");
            	break;
            }
            switch(input) {
            case 1:
            	insert();
            	break;
            case 2: 
            	delete();
            	break;
            case 3:
            	print();
            	break;
            }
        }
    }
    void insert(){
        Shape s;
        System.out.print("Line(1), Rect(2), Circle(3)>> ");
        int iInput = scanner.nextInt();
        if(iInput == 1){
            s = new Line();
        }
        else if(iInput == 2){
            s = new Rect();
        }
        else{
            s = new Circle();
        }

        if(head == null){
            head = s;
            tail = s;
        }
        else{
            tail.setNext(s);
            tail = s;
        }
    }
    public void delete() {
    	System.out.print("삭제할 도형의 위치 >>");
        int index = scanner.nextInt();
        Shape cur = head;
        Shape tmp = head;
        if(index == 1) {
            if(head == tail) {
                head = null;
                tail = null;
                return;
            }
            else {
                head = head.getNext();
                return;
            }
        }
        for(int i=1; i < index; i++) {
            tmp = cur;
            cur = cur.getNext();
            if(cur == null) {
                System.out.println("삭제할 수 없습니다.");
                return;
            }
        }
        tmp.setNext(cur.getNext());
    }
    public void print() {
        Shape s = head;
        while(s != null) {
            s.draw();
            s = s.getNext();
        }
    }
}

public class Editor {
    public static void main(String[] args) {
        GraphicEditor ge = new GraphicEditor();
        ge.run();
    }
}

 


 

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

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

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

[결과]

[소스 코드]

interface Shape{
	final double PI = 3.14;
	void draw();
	double getArea();
	default public void redraw() {
		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);
		donut.redraw();
		System.out.println("면적은 " + donut.getArea());
	}
}

 


 

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

[결과]

[소스 코드]

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;
	public Circle(int radius) {
		this.radius = radius;
	}
	public void draw() {
		System.out.println("반지름이 " + radius + "인 원입니다.");
	}
	public double getArea() {
		return PI * radius * radius;
	}
}
class Oval implements Shape{
	private int width, height;
	
	public Oval(int width, int height) {
		this.width = width;
		this.height = height;
	}
	public void draw() {
		System.out.println(width + "x" + height + "에 내접하는 타원입니다.");
	}
	public double getArea() {
		return width * height * PI;
	}	
}
class Rect implements Shape{
	private int width, height;
	
	public Rect(int width, int height) {
		this.width = width;
		this.height = height;
	}
	public void draw() {
		System.out.println(width + "x" + height + "에 내접하는 사각형입니다.");
	}
	public double getArea() {
		return width * height;
	}
}
public class ShapeTemp{
	static public 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[i].redraw();
		for(int i = 0; i < list.length; i++) System.out.println("면적은 " + list[i].getArea());
	}
}
반응형