Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

이지은님의 블로그

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

java 연습문제

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

queenriwon3 2024. 12. 12. 15:06

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

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;
    }
    protected int getColor() {return color;}
    public void printProperty(){
        System.out.println(getSize()+"인치 "+getColor()+"컬러");
    }
} 
public class Prac5_1 {
    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;
    }
    protected int getColor() {return color;}
    public void printProperty(){
        System.out.println(getSize()+"인치 "+getColor()+"컬러");
    }
} 
class IPTV extends ColorTV{
    private String address;
    public IPTV(String address, int size, int color){
        super(size, color);
        this.address = address;
    }
    protected String getAddress() {return address;}
    public void printProperty(){
        System.out.println("나의 IPTV는 "+getAddress()+"주소의 "+getSize()+"인치 "+getColor()+"컬러");
    }
} 
public class Prac5_2 {
    public static void main(String[] args) {
        IPTV iptv = new IPTV("192.1.1.2", 32, 2048);
        iptv.printProperty();
    }
}

 

 

3. Converter 클래스를 상속받아 원화를 달러로 변환하는 Won2Dollar 클래스를 작성하라. 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();
    }
}
class Won2Dollar extends Converter{
    public Won2Dollar(double ratio){
        this.ratio = ratio;
    }

    protected double convert(double src) {
        return src/ratio;
    }

    protected String getSrcString() {
        return "원";
    }

    protected String getDestString() {
        return "달러";
    }
    
}

public class Prac5_3 {
    public static void main(String[] args) {
        Won2Dollar tDollar = new Won2Dollar(1200);
        tDollar.run();
    }
}

 

4. Converter 클래스를 상속받아 km를 mile(마일)로 변환하는 Km2Mile 클래스를 작성하라. 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();
    }
}
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";
    }
    
}

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

 

 

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

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

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

public class Prac5_5 {
    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 int getX() {return x;}
    public int getY() {return y;}
    public Point(int x, int y) { this.x=x; this.y=y;}
    protected void move(int x, int y) { this.x=x; this.y=y;}
}

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

public class Prac5_5 {
    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 int getX() {return x;}
    public int getY() {return y;}
    public Point(int x, int y) { this.x=x; this.y=y;}
    protected void move(int x, int y) { this.x=x; this.y=y;}
}

class Point3D extends Point{
    private int z;
    public Point3D(int x, int y, int z){
        super(x,y);
        this.z=z;
    }
    protected int getZ() {return z;}
    public void moveUp(){ z++; }
    public void moveDown(){ z--; }
    public String toString(){
        return "("+getX()+","+getY()+","+getZ()+")의 점";
    }
    public void move(int x, int y, int z) {
        move(x,y);
        this.z=z;
    }
        
}
    
    public class Prac5_5 {
        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() 메소드를 포함하고 실행결과와 같이 출력되게 하라.

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

class PositivePoint extends Point{
    public PositivePoint(){
        super(0, 0);
    }
    public PositivePoint(int x, int y){
        super(x, y);
		if(x<0 || y<0)
			move(0,0);
		else
			return;
    }
    public void move(int x, int y){
        if(x<0 || y<0)
			return;
		else
			super.move(x, y);
    }
    public String toString(){
        return "("+getX()+","+getY()+")의 점";
    }
}
    
public class Prac5_5 {
    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(-10,-10);
        System.out.println(p2.toString()+"입니다.");
    }
    
}

 

 

9. 다음 Stack인터페이스를 상속받아 실수를 저장하는 StringStack 클래스를 구현하라. 그리고 다음 실행 사례와 같이 작동하도록 StackApp 클래스에 main()메소드를 작성하라.

import java.util.Scanner;

interface Stack{
    int length();
    int capacity();
    String pop();
    boolean push(String val);
}

class StringStack implements Stack{
    private String stackArray[];
    private int top;
    public StringStack(int num){
        stackArray = new String[num];
        top = 0;
    }

    @Override
    public String pop() {
        if (top==0){
            return "없음";
        } else {
            String popWord = stackArray[top-1];
            top--;
            return popWord;
        }
    }

    @Override
    public boolean push(String val) {
        if(top == stackArray.length){
            return false;
        } else {
            stackArray[top] = val;
            top++;
            return true;
        }
    }

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

    @Override
    public int capacity() {
        return stackArray.length;
    }

}

public class Prac5_9 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("총 스택 저장 공간의 크기 입력 >> ");
        int num = scanner.nextInt();
        StringStack ss = new StringStack(num);

        while (true) {
            System.err.print("문자열 입력 >> ");
            String ans = scanner.next();
            if(ans.equals("그만")){
                break;
            }
            
            if(!ss.push(ans)){
                System.out.println("스택이 꽉 차서 푸시 불가!");
            }
        }
        System.out.print("스택에 저장된 모든 문자열 팝 : ");
        int len = ss.length();
        for (int i = 0; i<len;i++){
            System.out.print(ss.pop()+" ");
        }
        System.out.println();

        scanner.close();
    }
}

 

 

10. 다음은 키와 값을 하나의 아이템으로 저장하고 검색 수정이 가능한 추상 클래스가 있다. PairMap을 상속받는 Dictionary 클래스를 구현하고, 이를 다음과 같이 활용하는 main() 메소드를 가진 클래스 DictionartApp도 작성하라.

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 top = 0;
	public Dictionary(int num) {
		keyArray = new String[num];
		valueArray = new String[num];
	}


    @Override
    String get(String key) {
        for(int i=0; i<top; i++) {
			if(key.equals(keyArray[i])) {
				return valueArray[i];
			}
		}
		return null;

    }

    @Override
    void put(String key, String value) {
        if(top == keyArray.length){
            System.out.println("put불가");
        } else {
            for (int i = 0; i<top; i++){
                if(keyArray[i].equals(key)){
                    valueArray[i] = value;
                    return;
                }
            }
            keyArray[top] = key;
            valueArray[top] = value;
            top++;
        }
    }

    @Override
    String delete(String key) {
        if(top == 0){
            System.out.println("delete불가");
        } else {
            for (int i = 0; i<top; i++){
                if(keyArray[i].equals(key)){
                    String pop = valueArray[i];
                    valueArray[i] = null;
                    return pop;
                }
            }
        }
        return "해당 키값없음";
    }

    @Override
    int length() {
        return top+1;
    }

}

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

 

 

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, 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 Sub extends Calc{
    @Override
    public int calculate() {
        return a-b;
    }
}

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

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

public class Prac5_11 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("두 정수와 연산자를 입력하시오>>");

        int a = scanner.nextInt();
        int b = scanner.nextInt();
        String cal = scanner.next();

        if(cal.equals("+")){
            Add add = new Add();
            add.setValue(a, b);
            System.out.println(add.calculate());
        } else if(cal.equals("-")){
            Sub sub = new Sub();
            sub.setValue(a, b);
            System.out.println(sub.calculate());
        } else if(cal.equals("*")){
            Mul mul = new Mul();
            mul.setValue(a, b);
            System.out.println(mul.calculate());
        } else if(cal.equals("/")){
            Div div = new Div();
            div.setValue(a, b);
            System.out.println(div.calculate());
        }
        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{
    @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 Shape head, tail;
    private Shape s;
    public void insert(int n){
        if(n==1){
            s = new Line();
        } else if(n==2){
            s = new Rect();
        } else if(n==3){
            s = new Circle();
        }
        if(head == null){
            head = s;
            tail = s;
        } else{
            tail.setNext(s);
            tail = s;
        }
    }
    public void delete(int n){
        Shape cur = head;   //현재노드
        Shape tmp = head;   //이전노드
        int i;
        if(n == 1){
            if(head == tail){
                head = null;
                tail = null;
            } else{
                head = head.getNext();
            }
        } else{
            for(i = 1; i<n; i++){
                tmp = cur;
                cur = cur.getNext();
                if(cur == null) {
                    System.out.println("삭제할 수 없습니다.");
                    return;
                }
            }
            tmp.setNext(cur.getNext());
        }
    }
    public void show(){
        Shape cur = head;   //현재노드
        while (cur != null) {
            cur.draw();
            cur = cur.getNext();
        }
    }

}

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

        Scanner scanner = new Scanner(System.in);
        System.out.println("그래픽 에디터 beauty을 실행합니다.");
        GraphicEditor beauty = new GraphicEditor();

        while (true) {
            System.out.print("삽입(1), 삭제(2), 모두보기(3), 종료(4)>>");
            int ans = scanner.nextInt();

            if(ans==4) break;
            if(ans==1) {
                System.out.print("Line(1), Rect(2), Circle(3)>>");
                int ansShape = scanner.nextInt();
                beauty.insert(ansShape);
            } else if(ans==2){
                System.out.print("삭제할 도형의 위치>>");
                int ansShape = scanner.nextInt();
                beauty.delete(ansShape);
            } else if(ans==3){
                beauty.show();
            }
        }
        System.out.println("beauty를 종료합니다.");
        scanner.close();
        
    }
}

 

 

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

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

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

}
public class Prac5_13 {
    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 size;
    public Circle(int size){
        this.size=size;
    }
    @Override
    public void draw() {
        System.out.println("반지름이 "+ size+"인 원입니다.");
    }
    @Override
    public double getArea() {
        return size * size * PI;
    }
}

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

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

public class Prac5_13 {
    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[i].redraw();
        for (int i=0; i<list.length; i++) System.out.println("면적은 "+ list[i].getArea());

    }
}