다라다라V
article thumbnail
728x90
반응형

[1~2]

package test.ch05;

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

💡 

 

[정답]

package test.ch05;

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(getSize() + "인치 " + color + "컬러");
    }
    
    // 해당 메서드는 2번 문제를 위해 필요
    public int getColor() { return color; }
    
    public static void main(String[] args) {
        ColorTV myTV = new ColorTV(32, 1024);
        myTV.printProperty();
    }
}

 

💡 

 

[정답]

package test.ch05;

public class IPTV extends ColorTV{
    private String ip;
    public IPTV(String ip, int size, int color) {
        super(size, color);
        this.ip = ip;
    }
    public void printProperty() {
        System.out.println("나의 IPTV는 " + ip + " 주소의 " + getSize() + "인치 " 
                + getColor() + "컬러");
    }

}

 

 

[3~4]

package test.ch05;

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 src = scanner.nextDouble();
        double dest = convert(src);
        System.out.println("변환 결과: " + dest + getDestString() + "입니다");
        scanner.close();
    }
}

 

💡 

 

[정답]

package test.ch05;

public class Won2Dollar extends Converter {

    // 입력받은 비율
    private double ratio;

    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 static void main(String[] args) {
        Won2Dollar toDollar = new Won2Dollar(1200);
        toDollar.run();
    }
}

 

💡 

 

[정답]

package test.ch05;

public class Km2Mile extends Converter{
    
        // 입력받은 비율
        private double ratio;
    
        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 static void main(String[] args) {
            Km2Mile toMile = new Km2Mile(1.6);
            toMile.run();
        }
}

 

[5~8]

package test.ch05;

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

 

💡 

 

[정답]

package test.ch05;

public class ColorPoint extends Point {
    private String color;

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

    public void setPoint(int x, int y) {
        move(x, y);
    }

    public void setColor(String color) {
        this.color = color;
    }

    // 문제에 알맞게 오버라이딩
    @Override
    public String toString() {
        return color + "색의 (" + getX() + ", " + getY() + ")의 점";
    }

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

 

💡 

 

[정답]

package test.ch05;

public class ColorPoint extends Point {
    private String color;

    public ColorPoint() {
        this(0, 0, "BLACK");
    }

    public ColorPoint(int x, int y) {
        this(x, y, "BLACK");
    }

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

    public void setPoint(int x, int y) {
        move(x, y);
    }

    public void setColor(String color) {
        this.color = color;
    }

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

    public static void main(String[] args) {
        ColorPoint zeroPoint = new ColorPoint();
        System.out.println(zeroPoint.toString() + "입니다.");

        ColorPoint cp = new ColorPoint(10, 10);
        cp.setPoint(5, 5);
        cp.setColor("RED");
        System.out.println(cp.toString() + "입니다.");
    }
}

 

💡 

 

[정답]

package test.ch05;

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

    public void moveDown() {
        z--;
    }

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

    public String toString() {
        return "(" + getX() + ", " + getY() + ", " + 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() + "입니다.");
    }

}

 

💡 

 

[정답]

package test.ch05;

public class PositivePoint extends Point {
    public PositivePoint() {
        super(0, 0);
    }

    public PositivePoint(int x, int y) {
        super(x, y);
        // 음수 공간에서는 생성되지 않도록 조치
        if (x < 0 || y < 0) {
            super.move(0, 0);
        }
    }

    @Override
    protected void move(int x, int y) {
        if (x >= 0 && y >= 0) {
            super.move(x, y);
        }
    }

    public String toString() {
        return "(" + getX() + ", " + 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(-10, -10);
        System.out.println(p2.toString() + "입니다.");
    }
}

 

💡 

 

[정답]

package test.ch05;

import java.util.Scanner;

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

public class StringStack implements Stack {
    private int capacity;
    private int length;
    private String[] stack;

    public StringStack(int capacity) {
        this.capacity = capacity;
        this.stack = new String[capacity];
        this.length = 0;
    }

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

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

    @Override
    public String pop() {
        // 스택이 비어있으면 null 리턴
        if (length == 0) {
            return null;
        }
        // 스택에서 꺼내기
        String val = stack[length - 1];
        length--;
        return val;
    }

    @Override
    public boolean push(String val) {
        // 스택이 꽉 차면 false 리턴 -> return으로 처리해 뒤 코드가 실행되지 않음
        if (length == capacity) {
            return false;
        }
        // 스택에 저장
        stack[length] = val;
        length++;
        return true;
    }

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

        // 크기를 입력받아 스택 생성
        System.out.print("총 스택 저장 공간의 크기 입력>> ");
        int size = scanner.nextInt();
        StringStack stringStack = new StringStack(size);

        // 스택에 문자열 저장
        while (true) {
            System.out.print("문자열 입력>> ");
            String input = scanner.next();
            // "그만"이 입력되면 종료
            if (input.equals("그만")) {
                break;
            }
            // 스택에 저장
            if (!stringStack.push(input)) {
                System.out.println("스택이 꽉 차서 푸시 불가!");
            }
        }

        // 저장된 모든 문자열 팝
        System.out.println("스택에 저장된 모든 문자열 팝: ");
        for (int i = 0; i < stringStack.length(); i++) {
            System.out.print(stringStack.pop() + " ");
        }
    }
}

 

💡 

 

[정답]

package test.ch05;

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

class Dictionary extends PairMap {
    private int capacity;
    private int length;
    private String[] keyArray;
    private String[] valueArray;

    public Dictionary(int capacity) {
        this.capacity = capacity;
        this.keyArray = new String[capacity];
        this.valueArray = new String[capacity];
        this.length = 0;
    }

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

    @Override
    void put(String key, String value) {
        for (int i = 0; i < length; i++) {
            if (keyArray[i].equals(key)) {
                valueArray[i] = value;
                return;
            }
        }
        keyArray[length] = key;
        valueArray[length] = value;
        length++;
    }

    @Override
    String delete(String key) {
        for (int i = 0; i < length; i++) {
            if (keyArray[i].equals(key)) {
                String value = valueArray[i];
                for (int j = i; j < length - 1; j++) {
                    keyArray[j] = keyArray[j + 1];
                    valueArray[j] = valueArray[j + 1];
                }
                length--;
                return value;
            }
        }
        return null;
    }

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

public class DictionaryApp {
    public static void main(String[] args) {
        Dictionary dic = new Dictionary(10);
        dic.put("황기태", "자바");
        dic.put("이재문", "파이썬");
        dic.put("이재문", "C++"); // 이재문의 값을 C++로 수정

        System.out.println("이재문의 값은 " + dic.get("이재문"));
        System.out.println("황기태의 값은 " + dic.get("황기태"));

        dic.delete("황기태"); // 황기태 아이템 삭제
        System.out.println("황기태의 값은 " + dic.get("황기태")); // 삭제된 아이템 접근
    }
}

 

💡 

 

[정답]

package test.ch05;

import java.util.Scanner;

abstract class Calc {
    protected int a, b;
    public void setValue(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public 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 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();

        // 연산자에 따라 객체 생성
        Calc calc = null;
        switch (op) {
            case "+":
                calc = new Add();
                break;
            case "-":
                calc = new Sub();
                break;
            case "*":
                calc = new Mul();
                break;
            case "/":
                calc = new Div();
                break;
        }

        // 객체에 값 설정 후 연산
        calc.setValue(a, b);
        System.out.println(calc.calculate());
    }
}

 

💡 

 

[정답]

한 클래스에 담고자 추상 클래스의 public 을 제거 했습니다. 또한 실제 실행 코드는 DaraSolution main()으로 뺐습니다.

package test.ch05;

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 GraphEditor {
    Scanner scanner = new Scanner(System.in);
    Shape head, tail;

    public GraphEditor() {
        head = null;
        tail = null;
    }

    public void insert(int shapeNum) {
        Shape shape;
        // 선택된 모양별 객체 만들기
        switch (shapeNum) {
            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 = shape;
        } else {
            tail.setNext(shape);
            tail = shape;
        }
    }

    public void delete(int delNum) {
        // 삭제할 도형이 없는 경우
        if (head == null) {
            System.out.println("삭제할 도형이 없습니다.");
            return;
        }
        // 삭제할 도형이 첫번째 도형인 경우
        if (delNum == 1) {
            if (head == tail) {
                head = null;
                tail = null;
            } else {
                head = head.getNext();
            }
        } else {
            // 삭제할 도형이 두번째 이후 도형인 경우
            Shape shape = head;
            for (int i = 1; i < delNum - 1; i++) {
                shape = shape.getNext();
                if (shape == null) {
                    System.out.println("삭제할 수 없는 위치입니다.");
                    return;
                }
            }
            // 삭제할 도형이 마지막 도형인 경우
            if (shape.getNext() == tail) {
                tail = shape;
                tail.setNext(null);
            } else {
                shape.setNext(shape.getNext().getNext());
            }
        }
    }

    public void print() {
        Shape shape = head;
        // 도형 출력
        while (shape != null) {
            shape.draw();
            shape = shape.getNext();
        }
    }

    public void run() {
        System.out.println("그래픽 에디터 beauty을 실행합니다.");
        while (true) {
            System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4)>> ");
            int num = scanner.nextInt();
            switch (num) {
                case 1:
                    System.out.print("Line(1), Rect(2), Circle(3)>> ");
                    int shapeNum = scanner.nextInt();
                    insert(shapeNum);
                    break;
                case 2:
                    System.out.print("삭제할 도형의 위치>> ");
                    int delNum = scanner.nextInt();
                    delete(delNum);
                    break;
                case 3:
                    print();
                    break;
                case 4:
                    System.out.println("beauty을 종료합니다.");
                    scanner.close();
                    return;
            }
        }
    }
}

public class DaraSolution {
    public static void main(String[] args) {
        GraphEditor editor = new GraphEditor();
        editor.run();
    }
}

 

 

💡 

 

[정답]

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

    @Override
    public void draw() { // 추상 메소드 구현
        System.out.println("반지름이 " + radius + "인 원입니다.");
    }

    @Override
    public double getArea() { // 추상 메소드 구현
        return radius * radius * PI;
    }
}

public class DaraSolution {
    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;

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

    @Override
    public void draw() { // 추상 메소드 구현
        System.out.println("반지름이 " + radius + "인 원입니다.");
    }

    @Override
    public double getArea() { // 추상 메소드 구현
        return radius * radius * PI;
    }
}

class Oval implements Shape {
    private int longAxis, shortAxis;

    public Oval(int longAxis, int shortAxis) {
        this.longAxis = longAxis;
        this.shortAxis = shortAxis;
    }

    @Override
    public void draw() {
        System.out.println(longAxis + "x" + shortAxis + "에 내접하는 타원입니다.");
    }

    @Override
    public double getArea() {
        return longAxis * shortAxis * PI;
    }
}

class Rect implements Shape {
    private int width, height;

    public Rect(int width, int height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public void draw() {
        System.out.println(width + "x" + height + "크기의 사각형입니다.");
    }

    @Override
    public double getArea() {
        return width * height;
    }
}

public class DaraSolution {
    public static void main(String[] args) {
        // Shape을 상속받는 클래스 객체를 저장하는 배열
        Shape[] list = new Shape[3];

        list[0] = new Circle(10);
        list[1] = new Oval(20, 30);
        list[2] = new Rect(10, 40);

        // for each 문을 이용하여 배열에 저장된 도형을 그린다.
        for (Shape s : list) {
            s.redraw();
        }
        // for each 문을 이용하여 배열에 저장된 도형의 면적을 구한다.
        for (Shape s : list) {
            System.out.println("면적은 " + s.getArea());
        }
    }
}

 

반응형
profile

다라다라V

@DaraDaraV

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!