Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

코딩로그

[명품 JAVA Programming] 제5장 상속 - 실습문제 본문

YJ/JAVA

[명품 JAVA Programming] 제5장 상속 - 실습문제

Team DAON 2021. 1. 5. 04:08

[1~2]

다음 TV 클래스가 있다.

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

[1번]

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

 

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

실행 결과
32인치 1024컬러
import java.util.*;

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

class ColorTV extends TV{//TV 클래스를 상속받은 ColorTV 클래스 선언
	private int color;//컬러 저장을 위한 변수 선언
	
	public ColorTV(int size, int color) {//TV 클래스의 size와 새로운 변수 color 초기화
		super(size);
		this.color = color;
		// TODO Auto-generated constructor stub
	}
	public void printProperty() {//문장 출력을 위한 함수 선언
		System.out.print(getSize()+"인치 "+color+"컬러");
	}
}
public class Main {
	public static void main(String[] args) {
		ColorTV myTV = new ColorTV(32, 1024);
		myTV.printProperty();
	}
}

실행 결과


[2번]

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

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

실행 결과
나의 IPTV는 192.1.1.2 주소의 32인치 2048컬러
import java.util.*;

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

class ColorTV extends TV{//TV 클래스를 상속받은 ColorTV 클래스 선언
	private int color;//컬러 저장을 위한 변수 선언
	
	public ColorTV(int size, int color) {//TV 클래스의 size와 새로운 변수 color 초기화
		super(size);
		this.color = color;
		// TODO Auto-generated constructor stub
	}
	public void printProperty() {//문장 출력을 위한 함수 선언
		System.out.print(getSize()+"인치 "+color+"컬러");
	}
	protected int getColor() {return color;}//색상 반환을 위한 함수 선언
}

class IPTV extends ColorTV{
	private String address;//주소 저장을 위한 변수 선언
	
	public IPTV(String address, int size, int color) {
		super(size, color);//부모 클래스의 변수 상속
		// TODO Auto-generated constructor stub
		this.address = address;//새로운 변수 초기화
	}
	
	public void printProperty() {//출력을 위한 함수 오버라이딩
		System.out.print("나의 IPTV는 " + address+ " 주소의 "+ getSize()+ "인치 "+ getColor() +"컬러");
		//문장 출력
	}
}
public class Main {
	public static void main(String[] args) {
		IPTV iptv = new IPTV("192.1.1.2", 32, 2048);
		iptv.printProperty();
	}
}

실행 결과


[3~4]

다음은 단위를 변환하는 추상 클래스 Converter이다.

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

실행 결과
원을 달러로 바꿉니다.
원을 입력하세요>> 24000
변환 결과: 20.0달러입니다
import java.util.*;

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

class Won2Dollar extends Converter {//Converter 클래스를 상속 받는 Won2Dollar 클래스 선언
	private double won;//입력받은 원을 저장할 변수 선언
	public Won2Dollar(double won) {
		// TODO Auto-generated constructor stub
		this.won = won;//입력받은 값으로 초기화
	}

	@Override
	protected double convert(double src) {//추상 메소드 정의
		// TODO Auto-generated method stub
		return src/won;//변환값 리턴
	}

	@Override
	protected String getSrcString() {//추상 메소드 정의
		// TODO Auto-generated method stub
		return "원";//원 리턴
	}

	@Override
	protected String getDestString() {//추상 메소드 정의
		// TODO Auto-generated method stub
		return "달러";//달러 리턴
	}
	
}
public class Main {
	public static void main(String[] args) {
		Won2Dollar toDollar = new Won2Dollar(1200);//1달러는 1200원
		toDollar.run();
	}
}

실행 결과


[4번]

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

public static void main(String[] args) {
		Km2Mile toMile = new Km2Mile(1.6);
		toMile.run();
}

실행 결과
Km을 mile로 바꿉니다.
Km을 입력하세요>> 30
변환 결과: 18.75mile입니다
import java.util.*;

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

class Km2Mile extends Converter {//Converter 클래스를 상속 받는 KM2Mile 클래스 선언
	private double km;//입력받은 km를 저장할 변수 선언
	public Km2Mile(double km) {
		// TODO Auto-generated constructor stub
		this.km = km;//입력받은 값으로 초기화
	}

	@Override
	protected double convert(double src) {//추상 메소드 정의
		// TODO Auto-generated method stub
		return src/km;//변환값 리턴
	}

	@Override
	protected String getSrcString() {//추상 메소드 정의
		// TODO Auto-generated method stub
		return "Km";//Km 리턴
	}

	@Override
	protected String getDestString() {//추상 메소드 정의
		// TODO Auto-generated method stub
		return "mile";//mile 리턴
	}
	
}
public class Main {
	public static void main(String[] args) {
		Km2Mile toMile = new Km2Mile(1.6);
		toMile.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 move(int x, int y) { this.x = x; this.y = y; }
}

[5번]

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

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

실행 결과
RED색의 (10,20)의 점입니다.
import java.util.*;

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; }
}
class ColorPoint extends Point {//Point 클래스를 상속받은 ColorPoint 클래스
	private String color;//색상 저장을 위한 변수 선언
	
	public ColorPoint(int x, int y, String color) {//초기화를 위한 생성자
		super(x, y);
		// TODO Auto-generated constructor stub
		this.color = color;//색상 초기화
	}
	public void setXY(int x, int y) {//입력받은 값으로 x, y값 갱신
		move(x, y);//Point 클래스의 함수 실행
	}
	public void setColor(String color) {//입력받은 값으로 color값 갱신
		this.color = color;
	}
	public String toString() {//문장 출력을 위한 함수, Point 클래스의 getX(), getY() 함수 사용
		return (color+"색의 ("+getX()+","+getY()+")의 점");
	}
}
public class 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 + "입니다.");
	}
}

실행 결과


[6번]

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

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()+"입니다.");
}
    
실행 결과
BLACK색의 (0,0)의 점입니다.
RED색의 (5,5)의 점입니다.
import java.util.*;

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; }
}
class ColorPoint extends Point {//Point 클래스를 상속받은 ColorPoint 클래스 선언
	private String color;//색 저장
	private int x;//x 저장
	private int y;//y 저장
	public ColorPoint() {//매개변수 없는 객체인 경우
		super(0,0);//(0,0)으로 초기화
		this.color = "BLACK";//BLACK으로 초기화
	}
	public ColorPoint(int x, int y) {//x, y가 지정된 경우
		super(x, y);//x, y 초기화
		// TODO Auto-generated constructor stub
        this.color = "BLACK";//BLACK으로 초기화
	}
	public void setXY(int x, int y) {//x, y를 갱신하기 위한 함수
		move(x, y);//함수 실행
	}
	public void setColor(String color) {//color를 갱신하기 위한 함수
		this.color = color;
	}
	public String toString() {//문장 출력
		return (color+"색의 ("+getX()+","+getY()+")의 점");
	}
}
public class 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()+"입니다.");
	}
}

실행 결과


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


실행 결과
(1,2,3)의 점입니다.
(1,2,4)의 점입니다.
(10,10,3)의 점입니다.
(100,200,300)의 점입니다.
import java.util.*;

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; }
}
class Point3D extends Point {//Point 클래스를 상속받은 Point3D 클래스 선언
	private int z;//z축 추가 
	
	public Point3D(int x, int y, int z) {//x, y, z 초기화
		super(x, y);
		this.z = z;
	}
	
	public void moveUp() { z++; }//z축의 값 1 증가하는 함수
	public void moveDown() { z--; }//z축의 값 1 감소하는 함수
	
	public void move(int x, int y, int z) {//x, y, z의 값 갱신용 함수
		move(x, y); //x, y값 갱신
		this.z = z;//z값 갱신
	}
	public String toString() {//문장 출력
		return ("("+getX()+","+getY()+","+z+")의 점");
	}
}
public class 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() + "입니다.");
	}
}

실행 결과


[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();
		System.out.println(p2.toString() + "입니다.");
}

실행 결과
(10,10)의 점입니다.
(10,10)의 점입니다.
(0,0)의 점입니다.

Hint!
Point 클래스의 move()를 PositivePoint 클래스에서 오버라이딩하여 재작성하고 
적절히 super.move()를 호출해야 한다.
PositivePoint의 2 개의 생성자에서도 적절히 super() 생성자와 super.move()를 호출해야 한다.
import java.util.*;

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; }
}
class PositivePoint extends Point {//Point 클래스를 상속받은 Point3D 클래스 선언
	
	public PositivePoint() { super(0,0); } //매개변수가 없는 객체인 경우 (0,0)으로 초기화
	
	public PositivePoint(int x, int y) {//매개변수가 있는 객체인 경우
		super(0,0);//(0,0)으로 초기화 후 조건에 따라 갱신
		move(x, y);//조건 검사 후 x, y 값 변경을 위한 함수 실행
	}
	public void move(int x, int y) {//x, y값 변경을 위한 함수
		if(x>=0&&y>=0) {//x, y가 음수가 아닌 경우
			super.move(x, y);//x, y 값 변경
		}
	}
	public String toString() {//문장 출력
		return ("("+getX()+","+getY()+")의 점");
	}
}
public class 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();
		System.out.println(p2.toString() + "입니다.");
		
	}
}

 

실행 결과


[9번]

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

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

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

총 스택 저장 공간의 크기 입력 >> 3
문자열 입력 >> hello
문자열 입력 >> sunny
문자열 입력 >> smile
문자열 입력 >> happy
스택이 꽉 차서 푸시 불가!
문자열 입력 >> 그만
스택에 저장된 모든 문자열 팝 : smile sunny hello 
import java.util.*;

interface Stack{
	int length(); // 현재 스택에 저장된 개수 리턴
	int capacity(); // 스택의 전체 저장 가능한 개수 리턴
	String pop(); // 스택의 톱(top)에 실수 저장
	boolean push(String val); // 스택의 톱(top)에 저장된 실수 리턴
}
class StringStack implements Stack {//Stack을 상속받는 StringStack 클래스
	private int len;//stack 배열의 개수 지정용 변수
	private int count;//현재 저장된 단어의 개수 저장용 변수
	private String[] stack;//단어 저장용 배열
	
	public StringStack(int len) {//생성자
		// TODO Auto-generated constructor stub
		this.len = len;
		this.count = 0;//0으로 초기화
		stack = new String[len];//len 크기를 가진 배열
	}

	@Override
	public int length() {//현재 저장된 단어의 수를 반환하는 함수
		// TODO Auto-generated method stub
		return count;
	}

	@Override
	public int capacity() {//배열의 크기를 반환하는 함수
		// TODO Auto-generated method stub
		return stack.length;
	}

	@Override
	public String pop() {//저장된 모든 문자열을 한 문장으로 반환하는 함수
		// TODO Auto-generated method stub
		String result = "스택에 저장된 모든 문자열 팝 : ";//형식에 맞춰 result 선언
		for(int i = count-1; i>=0; i--) {//역순으로 출력하기 위한 for문
			result += stack[i]+" ";//문자열 저장
		}
		return result;//문장 반환
	}

	@Override
	public boolean push(String val) {//문자열 저장을 위한 함수
		// TODO Auto-generated method stub
		stack[count] = val;//받아온 단어를 stack에 저장
		count++;//현재 저장된 개수 1 증가
		return true;
	}
	
}

public class StackApp{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.print("총 스택 저장 공간의 크기 입력 >> ");
		int len = scanner.nextInt();
		StringStack ss = new StringStack(len);//객체 생성
		
		while(true) {//break문을 만나기 전까지 반복
			System.out.print("문자열 입력 >> ");
			String s = scanner.next();
			if(s.equals("그만")) {//그만을 입력한 경우
				break;//while문에서 벗어나기
			}
			else if(ss.length() == ss.capacity()) {//스택이 꽉 찬 경우
				System.out.println("스택이 꽉 차서 푸시 불가!");//문장 출력
			}
			else {//단어를 저장할 수 있는 경우
				ss.push(s);//단어 저장 함수 호출
			}
		}
		System.out.print(ss.pop());//출력 형식에 맞춰 저장된 모든 문자열 출력
	}
}

실행 결과


[10번]

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

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(); // 현재 저장된 아이템의 개수 리턴
}

 

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

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("황기태"));
}

실행 결과
이재문의 값은 C++
황기태의 값은 자바
황기태의 값은 null
import java.util.*;

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(); // 현재 저장된 아이템의 개수 리턴
}

class Dictionary extends PairMap {//PairMap을 상속받은 Dictionary 클래스
	private int item;//저장된 아이템의 수
	private int len;//배열의 크기 저장
	public Dictionary(int len) {//생성자
		// TODO Auto-generated constructor stub
		this.len = len;
		this.item = 0;//저장된 아이템 수 0개로 초기화
		keyArray = new String[len];//입력받은 크기만큼 배열 생성
		valueArray = new String[len];//입력받은 크기만큼 배열 생성
	}

	@Override
	String get(String key) {//key에 해당하는 value값 반환하는 함수
		// TODO Auto-generated method stub
		for(int i = 0; i<keyArray.length; i++) {//key 배열의 크기만큼 반복
			if(keyArray[i].equals(key)) {//key값과 일치하는 값을 찾은 경우
				return valueArray[i];//해당 key에 대한 value 반환
			}
		}
		return null;//일치하는 key 값이 없는 경우, null 반환
	}

	@Override
	void put(String key, String value) {//key, value 갱신 또는 삽입 함수
		// TODO Auto-generated method stub
		boolean change = false;//갱신 여부 저장
		for(int i = 0; i<item; i++) {//현재 저장된 아이템의 개수만큼 반복
			if(key.equals(keyArray[i])) {//이미 저장된 key와 같은 경우
				valueArray[i] = value;//value 값 갱신
				change = true;//갱신 여부 true
			}
		}
		if(!change&&item<len) {//갱신하지 않고, 저장할 공간이 남아있는 경우
			keyArray[item] = key;//새로운 (키, 값) 삽입
			valueArray[item] = value;
			item++;//총 아이템의 수 증가
		}
		
	}

	@Override
	String delete(String key) {
		// TODO Auto-generated method stub
		String result = null;//value값 반환을 위한 변수
		for(int i = 0; i<keyArray.length; i++) {//배열의 크기만큼 반복
			if(key.equals(keyArray[i])) {//key와 일치하는 값이 있는 경우
				result = valueArray[i];//value값 result에 저장
				valueArray[i] = null;//value값 null로 갱신
			}
		}
		return result;//result에 저장된 값 반환
	}

	@Override
	int length() {
		// TODO Auto-generated method stub
		return item;//현재 저장된 아이템의 개수 반환
	}
	
}
public class DictionaryApp{
	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()를 호출하여 그 결과 값을 화면에 출력하면 된다고 생각하였다. 철수처럼 프로그램을 작성하라.

 

두 정수와 연산자를 입력하시오>>5 7 +
12
import java.util.*;

abstract class Calc {//상속을 위한 추상 클래스 선언
	protected int a;
	protected int b;
	abstract void setValue(int a, int b);
	abstract int calculate();
}

class Add extends Calc {//Calc 클래스를 상속받는 Add 클래스
	private int a, b;
	@Override//a, b값 저장
	void setValue(int a, int b) { this.a = a; this.b = b; }

	@Override//a, b의 합 반환
	int calculate() { return a+b; }
}

class Sub extends Calc {//Calc 클래스를 상속받는 Sub 클래스
	private int a, b;
	@Override//a, b값 저장
	void setValue(int a, int b) { this.a = a; this.b = b; }

	@Override//a, b의 차 반환
	int calculate() { return a-b; }
}

class Mul extends Calc {//Calc 클래스를 상속받는 Mul 클래스
	private int a, b;
	@Override//a, b값 저장
	void setValue(int a, int b) { this.a = a; this.b = b; }

	@Override//a, b의 곱 반환
	int calculate() { return a*b; }
}

class Div extends Calc {//Calc 클래스를 상속받는 Div 클래스
	private int a, b;
	@Override//a, b값 저장
	void setValue(int a, int b) { this.a = a; this.b = b; }

	@Override
	int calculate() { 
		if(b == 0)//나누는 값이 0인 경우
			return -1;//-1 리턴
		return a/b; //a/b의 몫 반환
	}
}

public class Main{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.print("두 정수와 연산자를 입력하시오>>");
		int a = scanner.nextInt();//정수 a
		int b = scanner.nextInt();//정수 b
		char c = scanner.next().charAt(0);//연산자
		Calc cal = null;//객체 선언
		
		switch(c) {//연산자에 따라 다른 객체
			case '+'://덧셈인 경우
				cal = new Add();
				break;
			case '-'://뺄셈인 경우
				cal = new Sub();
				break;
			case '*'://곱셈인 경우
				cal = new Mul();
				break;
			case '/'://나눗셈인 경우
				cal = new Div();
				break;
			default://잘못된 입력인 경우
				System.out.println("올바르지 않은 입력입니다.");
		}
		cal.setValue(a, b);//a, b의 값 전달을 위한 함수
		System.out.print(cal.calculate());//결과 출력
			
	}
}

실행 결과


[12번]

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

그래픽 에디터 beauty을 실행합니다.
삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>1
Line(1), Rect(2), Circle(3)>>2
삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>1
Line(1), Rect(2), Circle(3)>>3
삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>3
Rect
Circle
삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>2
삭제할 도형의 위치 >> 3
삭제할 수 없습니다.
삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>4
beauty을 종료합니다.

Hint!
Shape을 추상 클래스로 작성한 사례는 다음과 같다.
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(); // 추상 메소드
}

 

→ linked list랑 같은 원리를 사용하자

import java.util.*;

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 {//Shape를 상속받은 클래스
	String name = "Line";
	@Override
	public void draw() {//추상 메소드 정의
		// TODO Auto-generated method stub
		System.out.println("Line");//문장 출력
	}
}
class Rect extends Shape {//Shape를 상속받은 클래스
	String name = "Rect";
	@Override
	public void draw() {//추상 메소드 정의
		// TODO Auto-generated method stub
		System.out.println("Rect");//문장 출력
	}
}
class Circle extends Shape {//Shape를 상속받은 클래스
	String name = "Circle";
	@Override
	public void draw() {//추상 메소드 정의
		// TODO Auto-generated method stub
		System.out.println("Circle");//문장 출력
	}
}

public class GraphicEditor{
	private Shape head, tail; //시작, 끝 저장용
	
	public GraphicEditor() { //생성자
		head = null;  //시작
		tail = null; //끝
	}
	
	public void insert(int choice) {//삽입을 선택했을 때 실행하는 함수
		Shape graphic = null;
		switch(choice) {//choice의 값에 따라 다른 객체 생성
		case 1://1인 경우
			graphic = new Line();
			break;
		case 2://2인 경우
			graphic = new Rect();
			break;
		case 3://3인 경우
			graphic = new Circle();
			break;
		}
		if(head == null) { //저장된 값이 없는 경우, 시작과 끝이 새로운 객체를 가리킴
			head = graphic;
			tail = graphic;
		}
		else {//저장된 값이 있는 경우, 시작은 그대로 두고 끝만 새로운 객체와 연결
			tail.setNext(graphic);
			tail = graphic;
		}
	}
	
	public void print() {//전체 출력
		Shape shape = head;//처음에 저장된 객체로 이동
		
		while(shape != null) {//저장된 값이 있는 경우
			shape.draw();//문장 출력
			shape = shape.getNext();//연결된 다음 객체로 이동
		}
	}
	
	public void delete(int num) {//삭제를 선택한 경우 실행
		Shape now = head;//처음에 저장된 값
		Shape tmp = head;
		int count = 1;
		if(num == 1) {//첫번째 값을 삭제하는 경우
			if(head == tail) {//객체가 한 개인 경우, head와 tail 값을 null로 저장
				head = null;
				tail = null;
				return;
			}
			else { //한 개 이상인 경우
				head = head.getNext();//head가 두 번째 객체를 가리키게 함
				return;
			}
		}
		for(int i=1; i<num; i++) {
			tmp = now;//현재 객체 저장
			now = now.getNext();//연결된 객체로 이동
			if(now == null) {//입력받은 값이 연결된 수보다 큰 경우
				System.out.println("삭제할 수 없습니다.");//문장 출력
				return;
			}
			count = i;
		}
		if(count == num) {//끝에 저장된 값을 가리킬 때
			tmp.setNext(now.getNext());//now에 연결된 값을 tmp에 연결된 값에 저장
			tail = tmp;//끝이 가리키는 값에 저장
		}
		else //끝에 저장된 값을 가리키지 않는 경우
			tmp.setNext(now.getNext());//now에 연결된 값을 tmp에 연결된 값에 저장
		}
	public void run() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("그래픽 에디터 beauty을 실행합니다.");
		while(true) {
			System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>");
			int choice = scanner.nextInt();
			switch(choice) {
			case 1:
				System.out.print("Line(1), Rect(2), Circle(3)>>");
				int insertchoice = scanner.nextInt();
				insert(insertchoice);
				break;
			case 2:
	            System.out.print("삭제할 도형의 위치 >> ");
	            int num = scanner.nextInt();
	            delete(num);
	            break;
			case 3:
				print();
	            break;
			case 4:
	            System.out.println("beauty을 종료합니다.");
	            return;
			}
		}
	}
	public static void main(String[] args) {
		GraphicEditor editor = new GraphicEditor();
        editor.run();
	}
}

실행 결과


[13번]

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

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

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

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

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

class Circle implements Shape {//Shape 클래스를 상속받은 Circle 클래스
	private int r;//반지름 저장용 변수
	public Circle(int r) {//생성자
		this.r = r;//반지름 저장
	}
	@Override
	public void draw() {//반지름을 포함한 문장 출력용 함수
		// TODO Auto-generated method stub
		System.out.println(" 반지름이 "+r+"인 원입니다.");
	}

	@Override
	public double getArea() {//면적 반환 함수
		// TODO Auto-generated method stub
		return PI*r*r;
	}
	
}

public class Main{
	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를 추가 작성하고 전체 프로그램을 완성하라.

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());
}
import java.util.*;

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

class Circle implements Shape {//Shape 클래스를 상속받은 Circle 클래스
	private int r;//반지름 저장용 변수
	public Circle(int r) {//생성자
		this.r = r;//반지름 저장
	}
	@Override
	public void draw() {//반지름을 포함한 문장 출력용 함수
		// TODO Auto-generated method stub
		System.out.println(" 반지름이 "+r+"인 원입니다.");
	}

	@Override
	public double getArea() {//면적 반환 함수
		// TODO Auto-generated method stub
		return PI*r*r;
	}
}
class Oval implements Shape {//Shape 클래스를 상속받은 Oval 클래스
	private int a;//두 반지름 저장용 변수
	private int b;
	public Oval(int a, int b) {//생성자
		this.a = a;//입력받은 값 저장
		this.b = b;
	}
	@Override
	public void draw() {//두 반지름을 포함한 문장 출력용 함수
		// TODO Auto-generated method stub
		System.out.println(" "+a+"x"+b+"에 내접하는 타원입니다.");
	}

	@Override
	public double getArea() {//면적 반환 함수, 타원의 면적은 PI*a*b
		// TODO Auto-generated method stub
		return PI*a*b;
	}
}
class Rect implements Shape {//Shape 클래스를 상속받은 Rect 클래스
	private int a;//가로, 세로 길이 저장용 변수
	private int b;
	public Rect(int a, int b) {//생성자
		this.a = a;//가로, 세로 길이 저장
		this.b = b;
	}
	@Override
	public void draw() {//가로, 세로 길이를 포함한 문장 출력용 함수
		// TODO Auto-generated method stub
		System.out.println(" "+a+"x"+b+"크기의 사각형 입니다.");
	}

	@Override
	public double getArea() {//면적 반환 함수, 사각형의 면적은 가로*세로
		// TODO Auto-generated method stub
		return a*b;
	}
}
public class Main{
	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();//배열에 저장된 모든 값에 대한 redraw() 함수 호출
		for(int i = 0; i<list.length; i++) System.out.println("면적은 " + list[i].getArea());//배열에 저장된 모든 값에 대한 면적 출력 함수 호출
	}
}

실행 결과