[JAVA] 명품자바프로그래밍 5장 실습

2023. 3. 13. 21:50·개발자 세릴리/JAVA
728x90
반응형

 

5장 실습문제 1번 : TV를 상속받은 ColorTV 클래스를 작성하라.

class TV {
	//속성
	private int size;
	//메소드정의(생성자, getters&setters, toString)
	public TV() {}
	public TV(int size) {
		this.size = size;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	@Override
	public String toString() {
		return "TV [size=" + size + ", getSize()=" + getSize() + "]";
	}
}

class ColorTV extends TV {
	//속성
	private int color;
	//메소드정의(생성자)
	public ColorTV(int size, int color) {
		super(size);
		this.color=color;
	}
	//getProperty 추가
	public void printProperty() {
		System.out.println(super.getSize()+"인치 ,"+color()+"컬러");
	}
}

public class Ex5_TV {

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

}
 

 

5장 실습문제 2번 : ColorTV를 상속받은 IPTV 클래스를 작성하라.

class TV {
	//속성
	private int size;
	//메소드정의(생성자, getters&setters, toString)
	public TV() {}
	public TV(int size) {
		this.size = size;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	@Override
	public String toString() {
		return "TV [size=" + size + ", getSize()=" + getSize() + "]";
	}
}

class ColorTV extends TV {
	//속성
	private int color;
	//메소드정의(생성자)
	public ColorTV(int size, int color) {
		super(size);
		this.setColor(color);
	}
	//getProperty 추가
	public void printProperty() {
		System.out.println(super.getSize()+"인치 ,"+getColor()+"컬러");
	}
	public int getColor() {
		return color;
	}
	public void setColor(int color) {
		this.color = color;
	}
}

class IPTV extends ColorTV {
	//속성
	private String ip;
	//메소드정의(생성자)
	public IPTV(String ip, int size, int color) {
		super(size, color);
		this.ip = ip;
	}
	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}
	@Override
	public String toString() {
		return "IPTV [ip="+ip+", Size="+getSize()+", color="+getColor()+"]";
	}
	@Override
	public void printProperty() {
		System.out.print("ip=\""+ip+"\", ");
		System.out.println(super.getSize()+"인치 ,"+getColor()+"컬러");
	}
}

public class Ex5_TV {

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

 

5장 실습문제 3번 : Converter 클래스를 상속받아 원화를 달러로 변환하는 Won2Dollar 클래스를 작성하라.

import java.util.Scanner;

abstract class Converter {
	abstract protected double convert(double srs);
	abstract protected String getSrcString();
	abstract protected String getDestString();
	protected double ratio;
	
	public void run() {
		Scanner sc = new Scanner(System.in);
		System.out.println(getSrcString()+"을 "+getDestString()+"로 바꿉니다.");
		System.out.println("바꾸고싶은 "+getSrcString()+"화를 입력하세요 >> ");
		double val = sc.nextDouble();
		double res = convert(val);
		System.out.println("변환 결과 : "+res+getDestString()+"입니다.");
		sc.close();
	}
}

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

public class Ex5_03 {
	public static void main(String[] args) {
		//ratio 1200원 환율 설정
		Won2Dollar toDollar = new Won2Dollar(1200);
		toDollar.run();
	}
}
 
 

5장 실습문제 4번 : Converter 클래스를 상속받아 Km를 mile(마일)로 변환하는 Km2Mile 클래스를 작성하라.

import java.util.Scanner;

abstract class Converter2 {
	abstract protected double convert(double src);
	abstract protected String getSrcString();	
	abstract protected String getDestString();
	protected double ratio;	
	
	public void run() {
		Scanner sc = new Scanner(System.in);
		System.out.println(getSrcString() + "을 " + getDestString() + "로 바꿉니다.");
		System.out.print("바꾸고싶은 "+getSrcString() + " 수를 입력하세요>> ");
		double val = sc.nextDouble();
		double res = convert(val);
		System.out.println("변환 결과: " + res + getDestString() + "입니다.");
		sc.close();
	}
}

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


public class Ex5_04 {
	public static void main(String[] args) {
		//ratio는 1마일이 1.6Km이기때문에 1.6으로 설정 
		Km2Mile toMile = new Km2Mile(1.6);
		toMile.run();
	}
}
 
 

5장 실습문제 5번 : Point 클래스를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라.

class Point {
	private int x,y;
	
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	//getters&setters
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}
	protected void move(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

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);
	}
	//getters&setters
	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
	//toString
	@Override
	public String toString() {
		return getColor() + "색의 , (" + getX() + "," + getY() + ")의 점";
	}
}

public class Ex5_5 {

	public static void main(String[] args) {
		ColorPoint cp = new ColorPoint(5, 5, "Yellow");
		String str1 = cp.toString();
		System.out.println("처음 정의된 colorPoint는 "+str1+"입니다.");
		cp.setXY(10,20);
		cp.setColor("Red");
		String str2 = cp.toString();
		System.out.println("이동한 colorPoint는 "+str2+"입니다.");
	}
}
 
 
 
 

5장 실습문제 6번 : Point 클래스를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라.

class Point {
	private int x,y;
	
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	//getters&setters
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}
	protected void move(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

class ColorPoint extends Point {
	private String color;

	public ColorPoint(int x, int y) {
		super(x, y);
	}
	
	public ColorPoint() {
		super(0,0);
		this.color = "Black";
	}

	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);
	}
	//getters&setters
	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
	//toString
	@Override
	public String toString() {
		return getColor() + "색의 , (" + getX() + "," + getY() + ")의 점";
	}
}

public class Ex5_6 {

	public static void main(String[] args) {
		//기본생성자로 정의한 (0,0)점
		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("새로 이동한 colorPoint는 "+cp.toString()+"입니다.");
	}
}
 
 
 

5장 실습문제 7번 : Point 클래스를 상속받아 3차원의 점을 나타내는 Point3D 클래스를 작성하라.

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 += 1;
	}
	public void moveDown() {
		this.z -= 1;
	}
	
	public void setXY(int x, int y) {
		super.move(x, y);
	}
	
	public void move(int x, int y, int z) {
		super.move(x, y);
		this.z = z;
	}
	
	@Override
	public String toString() {
		return "(" + getX() + "," + getY() + "," + z + ")의 점";
	}
}

public class Ex5_7 {

	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();
		System.out.println("한 칸 아래로 이동한 점은 "+p.toString()+" 입니다.");
		p.move(10, 10);
		System.out.println("x,y좌표가 이동한 점은 "+p.toString()+" 입니다.");
		p.move(100, 200, 300);
		System.out.println("x,y,z좌표가 이동한 점은 "+p.toString()+" 입니다.");
	}

}
 
 

5장 실습문제 8번 : Point를 상속받아 양수의 공간에서만 점을 나타내는 PositivePoint 클래스를 작성하라.

class PositivePoint extends Point {
	public PositivePoint() {super(0,0);}
	
	public PositivePoint(int x, int y) {
		super(x,y);
		//x나 y가 음수면 초기값을 0으로 세팅
		if(x<0) {
			if(y<0) {super.move(0, 0);}
			else {super.move(0, y);}
		}
		else if(y<0) {super.move(x, 0);}
		else {super.move(x, y);}
	}
	
	@Override
	public void move(int x, int y) {
		if(x>=0&&y>=0) {super.move(x, y);}
		else {}
	}

	@Override
	public String toString() {
		return "(" + getX() + "," + getY() + ")의 점";
	}
}

public class Ex5_8 {

	public static void main(String[] args) {
		PositivePoint p = new PositivePoint();
		p.move(10, 10);
		System.out.println(p.toString()+"입니다.");
		//음수가 포함된 점 p1 생성
		PositivePoint p1 = new PositivePoint(-5,5);
		//x값이 0으로 세팅된다
		System.out.println(p1.toString()+"입니다.");
		//음수가 포함된 점 p2 생성
		PositivePoint p2 = new PositivePoint(-10,-10);
		//x,y값이 0으로 세팅된다
		System.out.println(p2.toString()+"입니다.");
	}
}
 
 
 
 

5장 실습문제 9번 : Stack 인터페이스를 상속받아 실수를 저장하는 StringStack 클래스를 구현하라.

import java.util.Scanner;

interface Stack {
	// 현재 스택에 저장된 개수
	int length(); 

	// 스택의 전체 저장 가능한 개수
	int capacity(); 

	// 스택에 문자열 저장될때마다 배열 줄이
	String pop(); 

	// 스택에 문자열을 더 채울 수 있는지 참, 거짓 판
	boolean push(String val); 
}

class StackApp implements Stack {
	private int length, capacity;
	String[] arr;

	public StackApp(int n) {
		arr = new String[n];
		length = 0;
		capacity = n;
	}

	@Override
	public int length() {
		return length;
	}

	@Override
	public int capacity() {
		return capacity;
	}

	@Override
	public String pop() {
		return arr[--length];
	}

	@Override
	public boolean push(String val) {
		if (length == capacity) {
			System.out.println("스택이 꽉 차서 더 이상 넣을 수 없습니다!");
			return false;
		} else {
			arr[length++] = val;
			return true;
		}
	}
}

public class Ex5_09 {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.print("총 스택 저장 공간의 크기 입력 >> ");
		int n = sc.nextInt();

		StackApp app = new StackApp(n);

		while (true) {
			System.out.print("문자열 입력 >> ");
			String str = sc.next();
			if (str.equals("그만"))
				break;
			app.push(str);

		}
		
		System.out.print("스택에 저장된 모든 문자열 출력 : ");
		for (String a : app.arr) {
			System.out.print(a + " ");
		}
	}
}
 
 
 
 

5장 실습문제 10번 : PairMap을 상속받는 Dictionary 클래스를 구현하고, 이를 활용하는 main() 메소드를 가진 클래스를 작성하라.

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 item;
	
	public Dictionary(int n) {
		keyArray = new String[n];
		valueArray = new String[n];
		this.item = 0;
	}
	@Override
	public String get(String key) {
		for(int i=0; i<keyArray.length; i++) {
			if(key.equals(keyArray[i]))
				return keyArray[i];
		}
		return null;
	}
	@Override
	public void put(String key, String value) {
		for(int i=0; i<keyArray.length; i++) {
			if(key.equals(keyArray[i])) {
				keyArray[i] = key;
				valueArray[i] = value;
				return;
			}
		}
		keyArray[item] = key;
		valueArray[item] = value;
		item++;
	}
	@Override
	public String delete(String key) {
		for(int i=0; i<keyArray.length; i++) {
			if(key.equals(keyArray[i])) {
				String val = valueArray[i];
				keyArray[i] = null;
				valueArray[i] = null;
				return val;
			}
		}
		return null;
	}
	@Override
	public int length() {
		return item;
	}
}

public class Ex5_10 {
	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("김둘리"));
	}
}
 
 
 
 

5장 실습문제 11번 : 추상 클래스 Calc를 작성하고 이를 상속 받아 연산을 처리하는 Add, Sub, Mul, Div 클래스를 작성하라.

import java.util.Scanner;

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

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

class Min extends Calc {
	@Override
	public int calculate() {
		return a-b;
	}
}

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

class Sub extends Calc {
	@Override
	public int calculate() {
		return a/b;
	}
}

public class Ex5_11 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("두 정수와 연산자를 입력하세요 >> ");
		int a = sc.nextInt();
		int b = sc.nextInt();
		String op = sc.next();
		
		Calc cal;
		switch(op) {
		case "+":
			cal = new Add();
			break;
		case "-":
			cal = new Min();
			break;
		case "*":
			cal = new Mul();
			break;
		case "/":
			cal = new Sub();
			break;
		default:
			System.out.println("잘못 입력하셨습니다.");
			return;
		}
		cal.setValue(a, b);
		System.out.println(cal.calculate());
	}
}
 

 

5장 실습문제 12번 : 텍스트로 입출력하는 간단한 그래픽 편집기를 만들어보자.

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 {
	@Override
	public void draw() {
		System.out.println("Line");
	}
}
class Rect extends Shape {
	@Override
	public void draw() {
		System.out.println("Rect");
	}
}
class Circle extends Shape {
	@Override
	public void draw() {
		System.out.println("Circle");
	}
}

class GraphicEditor {
	private String name;
	Scanner sc = new Scanner(System.in);
	private Shape head = null, tail = null;
	
	public GraphicEditor(String name) {
		this.name = name;
	}
	
	public void run() {
		System.out.println("그래픽 에디터 "+name+"을(를) 실행합니다.");
		while(true) {
			System.out.println("1.삽입 2.삭제 3.모두 보기 4.종료 >> ");
			int num = sc.nextInt();
			switch(num) {
			case 1:
				System.out.println("1.Line 2.Rect 3.Circle >> ");
				int spNum = sc.nextInt();
				insert(spNum);
				break;
			case 2:
				System.out.println("삭제할 도형의 위치 >> ");
				int delNum = sc.nextInt();
				delete(delNum);
				break;
			case 3:
				print(); break;
			case 4:
				System.out.println(name+"을(를) 종료합니다.");
				return;
			default:
				System.out.println("잘못 입력하셨습니다.");
			}
		}
	}
	
	public void insert(int spNum) {
		Shape shape;
		switch(spNum) {
		case 1:
			shape = new Line();
			break;
		case 2:
			shape = new Rect();
			break;
		case 3:
			shape = new Circle();
			break;
		default:
			System.out.println("잘못 입력하셨습니다.");
			return;
		}
		if(head==null) {
			head = shape;
			tail = head;
		}
		else {
			tail.setNext(shape);
			tail = shape;
		}
	}
	
	public void delete(int delNum) {
		Shape current = head;
		Shape a = head;
		int i;
		if(delNum==1) {
			if(head==tail) {
				head = null;
				tail = null;
				return;
			}
			else {
				head = head.getNext();
				return;
			}
		}
		for(i=1; i<delNum; i++) {
			a = current;
			current = current.getNext();
			if(current == null) {
				System.out.println("삭제할 수 없습니다.");
				return;
			}
		}
		if(i==delNum) {
			a.setNext(current.getNext());
			tail = a;
		}
		else {
			a.setNext(current.getNext());
		}
	}
	public void print() {
		Shape shape = head;
		while(shape != null) {
			shape.draw();
			shape = shape.getNext();
		}
	}
}

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

5장 실습문제 13번 : 인터페이스 Shape을 구현한 클래스 Circle를 작성하라.

interface Shape {
	final double PI = 3.14;

	void draw();

	double getArea(); 

	//디폴트값 설정 
	default public void redraw() { 
		System.out.println("=== 다시 그립니다. ===");
		draw();
	}
}

class Circle implements Shape {
	private int radius;

	public Circle(int radius) {
		this.radius = radius;
	}

	public void draw() {
		System.out.println("=== 도형을 그립니다. ===");
		System.out.println("반지름이 " + radius + "인 원입니다.");
	}

	public double getArea() {
		return radius * radius * PI;
	}
}

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

5장 실습문제 14번 : 13번 문제의 Shape 인터페이스를 구현한 클래스 Oval, Rect를 추가 작성하라.

interface Shape {
	final double PI = 3.14;

	void draw();

	double getArea(); 

	//디폴트값 설정 
	default public void redraw() { 
		System.out.println("=== 다시 그립니다. ===");
		draw();
	}
}

class Circle implements Shape {
	private int radius;

	public Circle(int radius) {
		this.radius = radius;
	}

	public void draw() {
		System.out.println("=== 도형을 그립니다. ===");
		System.out.println("반지름이 " + radius + "인 원입니다.");
	}

	public double getArea() {
		return radius * radius * PI;
	}
}

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("=== 도형을 그립니다. ===");
		System.out.println("가로 "+width+", 세로 " + 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("=== 도형을 그립니다. ===");
		System.out.println("가로 "+width+", 세로 " + height + "인 사각형입니다.");
	}

	public double getArea() {
		return width * height;
	}
}
public class Ex5_14 {

	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(Shape a : list) {
			a.draw(); 
			System.out.println("면적은 "+a.getArea());
		}
	}
}
 
 
 

 

 

728x90
반응형

'개발자 세릴리 > JAVA' 카테고리의 다른 글

[JAVA] 명품자바프로그래밍 6장 실습  (0) 2023.03.16
[JAVA] 명품자바프로그래밍 4장 실습  (0) 2023.02.28
[JAVA] 명품자바프로그래밍 3장 실습  (2) 2023.02.25
[JAVA] 명품자바프로그래밍 2장 실습  (0) 2023.02.23
'개발자 세릴리/JAVA' 카테고리의 다른 글
  • [JAVA] 명품자바프로그래밍 6장 실습
  • [JAVA] 명품자바프로그래밍 4장 실습
  • [JAVA] 명품자바프로그래밍 3장 실습
  • [JAVA] 명품자바프로그래밍 2장 실습
세릴리
세릴리
  • 세릴리
    세리의 데이터베이스 세상
    세릴리
  • 전체
    오늘
    어제
    • 분류 전체보기 (87)
      • 개발자 세릴리 (65)
        • 비전공자 한 입 지식 (12)
        • 코딩테스트 (24)
        • 스펙업 (15)
        • JAVA (5)
        • 일상 (9)
      • 파이어족 세릴리 (21)
        • 블로그 운영 (3)
        • 각종 양식 공유 (1)
        • 돈되는 정보 공유 (17)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준
    java 공부
    adsp 벼락치기
    비전공자 개발자
    JAVA 책 추천
    프로그래밍 공부
    비전공자 개발
    이슈
    현대오토에버 코딩테스트
    명품자바프로그래밍
    JAVA 개발공부
    명품자바프로그래밍 해설
    adsp 자료
    현대 코딩테스트
    adsp 수험표
    개발자되는법
    현대 코테
    현대오토에버 코테
    비전공 개발자
    Softeer 문제 풀이
    adsp 독학
    오늘 이슈
    개발자 공부
    명품자바프로그래밍 정답
    현대모비스 코딩테스트
    adsp 공부법
    현대자동차 코딩테스트
    개발자 이직
    Java 문제
    softeer java 풀이
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
세릴리
[JAVA] 명품자바프로그래밍 5장 실습
상단으로

티스토리툴바