본문 바로가기
학부공부/Java_Basic

Chapter 11. Inheritance and Polymorphism[Java Basic]

by sonpang 2021. 11. 6.
반응형

11.A - Person, Student, Employee, Faculty, 그리고 Staff 클래스

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

Person이라는 이름의 클래스와, 이를 상속받는 Student와 Employee라는 이름의 클래스를 만드시오. Employee를 상속받아 Faculty와 Staff라는 이름을 갖는 클래스를 만드시오. 사람(Person)에게는 이름, 주소, 전화 번호, 이메일 주소가 있다. 학생(Student)에게는 학년 상태가 있다.(freshman, sophomore, junior, 혹은 senior). 이 상태를 상수로 지정하시오. 피고용인(Employee)에게는 사무실, 봉급, 채용일자가 있다. 채용일자를 정의하기 위해 연습문제 10.14의 MyDate 클래스를 이용하시오. 교수진(Faculty)에게는 근무 시간, 계급이 있다. 직원(Staff)에게는 칭호(title)가 있다. toString 메소드를 오버라이드하여 클래스 이름과 사람의 이름을 표시하시오. 클래스들의 UML 다이어그램을 그리고 구현하시오. Person, Student, Employee, Faculty, 그리고 Staff를 생성하고, toString() 메소드를 호출하는 테스트 프로그램을 작성하시오.

(The Person, Student, Employee, Faculty, and Staff classes) Design a class named Person and its two subclasses named Student and Employee. Make Faculty and Staff subclasses of Employee. A person has a name, address, phone number, and email address. A student has a class status (freshman, sophomore, junior, or senior). Define the status as a constant. An employee has an office, salary, and date hired. Use the MyDate class defined in Programming Exercise 10.14 to create an object for date hired. A faculty member has office hours and a rank. A staff member has a title. Override the toString method in each class to display the class name and the person’s name. Draw the UML diagram for the classes and implement them. Write a test program that creates a Person, Student, Employee, Faculty, and Staff, and invokes their toString() methods.

 

INPUT

* Line 1 : Person의 수 N (1~1,000)

* Line 2 ~ N+1 : 탭으로 구분된 name, address, phoneNumber, email, class, title

- name, address, phoneNumber, email, class, title는 공백없이 길이가 50을 넘지 않는 문자열

 

OUTPUT

Sample Output 형식으로 출력

 

SAMPLE INPUT

5

Milass 64642 010-2808-2327 Milass24@daum.com Staff ACADEMIC_AFFAIRS

Elijah 98778 010-1807-4212 Elijah18@yahoo.com Student SOPHOMORE

Connor 19331 010-6685-1955 Connor28@gmail.com Staff BUSINESS_ADMINISTRATIVE_AFFAIRS

Evelynss 71931 010-6929-5816 Evelynss2@daum.com Employee ASSOCIATE_PROFESSOR

Gracess 47917 010-7317-5923 Gracess26@hotmail.com Employee PROFESSOR

 

SAMPLE OUTPUT

Milass is Staff

Elijah is Student

Connor is Staff

Evelynss is Faculty

Gracess is Faculty

 

SAMPLE CODE
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;

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

        ArrayList<Person> list = new ArrayList<>();
        int N = sc.nextInt();
        sc.nextLine();
        for (int n = 0; n < N; n++) {
            String[] items = sc.nextLine().split("\t");
            Person p = null;
            if (items[4].equals("Student")) {
                Student p1 = new Student();
                if (items[5].equals("FRESHMAN")) p1.status = Student.FRESHMAN;
                else if (items[5].equals("SOPHOMORE")) p1.status = Student.SOPHOMORE;
                else if (items[5].equals("JUNIOR")) p1.status = Student.JUNIOR;
                else if (items[5].equals("SENIOR")) p1.status = Student.SENIOR;
                p = p1;
            } else if (items[4].equals("Employee")) {
                Faculty p1 = new Faculty();
                if (items[5].equals("LECTURER")) p1.rank = Faculty.LECTURER;
                else if (items[5].equals("ASSISTANT_PROFESSOR")) p1.rank = Faculty.ASSISTANT_PROFESSOR;
                else if (items[5].equals("ASSOCIATE_PROFESSOR")) p1.rank = Faculty.ASSOCIATE_PROFESSOR;
                else if (items[5].equals("PROFESSOR")) p1.rank = Faculty.PROFESSOR;
                p = p1;
            } else if (items[4].equals("Staff")) {
                Staff p1 = new Staff();
                p1.title = items[5];
                p = p1;
            }
            p.name = items[0];
            p.address = items[1];
            p.phoneNumber = items[2];
            p.email = items[3];
            list.add(p);
        }
        for (Person p : list) System.out.println(p);
    }
}

YOUR_CODE

 

class Person{
    String name, address, phoneNumber, email;
    Person(){ }
    Person(String iname, String iaddress, String iphone, String iemail){
        this.name = iname;
        this.address = iaddress;
        this.phoneNumber = iphone;
        this.email = iemail;
    }
    public String getName(){
        return name;
    }
    public String getAddress(){
        return address;
    }
    public String getPhone(){
        return phoneNumber;
    }
    public String getEmail(){
        return email;
    }
    public void setName(String iname) {
        name = iname;
    }
    public void setAddress(String iaddress) {
        address = iaddress;
    }
    public void setPhone(String iphoneNumber) {
        phoneNumber = iphoneNumber;
    }
    public void setEmail(String iemail) {
        email = iemail;
    }
    public String toString() {
        return name + " is ";
    }
}
class Student extends Person{
    int status;
    final static int FRESHMAN = 1;
    final static int SOPHOMORE = 2;
    final static int JUNIOR = 3;
    final static int SENIOR = 4;
    Student(){ }
    Student(String iname, String iaddress, String iPhoneNumber, String iemail, int istatus){
        super(iname,iaddress,iPhoneNumber,iemail);
        status = istatus;
    }
    public String getStatus(){
        switch(status){
            case 1 : return "FRESHMAN";
            case 2 : return "SOPHOMORE";
            case 3 : return "JUNIOR";
            case 4 : return "SENIOR";
        }
        return "";
    }
    public String toString(){
        return super.toString() + "Student";
    }
 
}
 
class Employee extends Person{
    String office;
    double salary;
    java.util.Date date;
    public String getOffice() {
        return office;
    }
 
    public void setOffice(String office) {
        this.office = office;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }
 
    public java.util.Date getDate() {
        return date;
    }
 
    public void setDate(java.util.Date date) {
        this.date = date;
    }
    public String toString () {
        return super.toString() + "Employee";
    }
}
class Faculty extends Person{
    int rank;
    String hours;
    final static int LECTURER = 1;
    final static int ASSISTANT_PROFESSOR = 3;
    final static int ASSOCIATE_PROFESSOR = 2;
    final static int PROFESSOR = 4;
    Faculty(){ }
    Faculty(String iname, String iaddress, String iPhoneNumber, String iemail, int isrank){
        super(iname,iaddress,iPhoneNumber,iemail);
        this.rank = isrank;
    }
    public String getRank() {
        switch (rank) {
            case 1:
                return "LECTURER";
            case 2:
                return "ASSISTANT_PROFESSOR";
            case 3:
                return "ASSOCIATE_PROFESSOR";
            case 4:
                return "PROFESSOR";
        }
        return "";
    }
    public String getHours () {
        return hours;
    }
    public void setHours (String hours){
        this.hours = hours;
    }
    public String toString () {
        return super.toString() + "Faculty";
    }
 
}
class Staff extends Person{
    String title;
    public String getTitle(){
        return title;
    }
    public void setTitle(String title){
        this.title = title;
    }
    public String toString () {
        return super.toString() + "Staff";
    }
}

 

 

11.B - 볼록 다각형의 넓이

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

다각형의 두 점을 잇는 선분들이 다각형 내부에 있따면 이를 볼록 다각형이라 한다. 볼록 다각형의 좌표를 시계 방향으로 입력받고, 면적을 출력하는 프로그램을 작성하시오. 다음은 프로그램의 실행 예시이다.

A polygon is convex if it contains any line segments that connects two points of the polygon. Write a program that prompts the user to enter the number of points in a convex polygon, then enter the points clockwise, and display the area of the polygon. Here is a sample run of the program:

 

INPUT

* Line 1 : 다각형의 변의 수 T (1~30)

* Line 2 ~ T+1 : 다각형의 꼭지점 좌표를 나타내는 x y

- x, y는 0보다 크고 1,000 보다 작다

 

OUTPUT

* Line 1 : 다각형의 넓이를 반올림해서 소수점 두자리까지 출력

 

SAMPLE INPUT

8

395 304

454 255

467 169

427 93

327 88

275 150

247 213

286 315

 

SAMPLE OUTPUT

The total area is 37718.00

 

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt(), i;
        double data[][] = new double[n][2], a = 0;
        for (i = 0; i < n; i++) {
            data[i][0] = input.nextInt();
            data[i][1] = input.nextInt();
        }
        for (i = 1; i < n - 1; i++)
            a += area(data[0], data[i], data[i+1]);
        System.out.printf("The total area is %.2f",Math.round(a*100)/100.0);
        System.out.println();
    }
    public static double area(double p1[], double p2[], double p3[]){
        return Math.abs((p2[0] - p1[0]) * (p3[1] - p1[1]) - (p3[0] - p1[0]) * (p2[1] - p1[1])) / 2;
    }
}
반응형

 

 

11.C - 대수: 제곱수

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

m이 주어졌을때 m * n를 정수의 제곱수로 만드는 최소의 n을 찾아라.

Write a program that prompts the user to enter an integer m and find the smallest integer n such that m * n is a perfect square. (Hint: Store all smallest factors of m into an array list. n is the product of the factors that appear an odd number of times in the array list. For example, consider m = 90, store the factors 2, 3, 3, 5 in an array list. 2 and 5 appear an odd number of times in the array list. So, n is 10.) Here are sample runs:

 

INPUT

* Line 1 : 테스트케이스 T (1~1,000)

* Line 2 ~ T+1 : m (1~10,000 범위의 정수)

 

OUTPUT

* Line 1 ~ T : m * n 을 Sample Output 형식으로 출력

 

SAMPLE INPUT

3

90

1500

63

 

SAMPLE OUTPUT

900 = 90 x 10

22500 = 1500 x 15

441 = 63 x 7

 

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt(), i, data[] = new int[n], ans;
        for(i = 0; i < n; i++)
            data[i] = input.nextInt();
        for(i = 0; i < n; i++){
            ans = find(data[i]);
            System.out.println(ans*data[i] + " = " + data[i] + " x " + ans);
        }
    }
    public static int find(int n){
        for(int i = 1; ;i++){
            double d = Math.sqrt(n*i);
            if(d == Math.floor(d))
                return i;
        }
    }
}

 

 

11.D - Triangle 클래스

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

GeometricObject 클래스를 상속받은 Triangle이라는 이름의 클래스를 만드시오. 이 클래스는 다음을 포함한다 :

변수 side1, side2, side3. 삼각형의 세 변을 의미하는 double형 변수이며, 디폴트 값은 1.0이다.

인자를 받지 않는 생성자(constructor). 디폴트 값을 갖는 삼각형을 만든다.

인자를 받는 생성자(constructor). side1, side2, side3를 지정하며 삼각형을 만든다.

세 개의 변수에 접근하는 접근자(accessor), 삼각형의 넓이를 반환하는 메소드 getArea(), 삼각형의 둘레의 길이를 반환하는 메소드 getPerimeter(), 삼각형에 대한 묘사를 반환하는 메소드 toString(). 삼각형의 넓이를 계산하는 공식은 연습문제 2.19를 참고하시오.

toString() 메소드는 다음과 같이 구한한다 : return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;

(The Triangle class) Design a class named Triangle that extends GeometricObject. The class contains:

Three double data fields named side1, side2, and side3 with default values 1.0 to denote three sides of the triangle.

A no-arg constructor that creates a default triangle.

A constructor that creates a triangle with the specified side1, side2, and side3.

The accessor methods for all three data fields.

A method named getArea() that returns the area of this triangle.

A method named getPerimeter() that returns the perimeter of this triangle.

A method named toString() that returns a string description for the triangle. For the formula to compute the area of a triangle, see Programming Exercise 2.19.

The toString() method is implemented as follows: return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;

 

INPUT

* Line 1 : 테스트케이스 T (1~1,000)

* Line 2 ~ T+1 : side1 side2 side3 color filled

- side1, side2, side3 는 0~10사이의 실수

- color는 공백없이 길이가 50을 넘지 않는 문자열

- filled는 true 또는 false

 

OUTPUT

Sample Output 형식으로 출력 숫자는 소숫점 둘째자리 까지 출력하시오. (DecimalFormat("##.00") 참고)

 

SAMPLE INPUT

5

5.22856359077 8.64369661889 7.81208777215 red false

4.73859498495 5.28984483026 6.43911724765 blue true

9.85370908953 7.66252345724 4.89050910369 orange true

6.28459944776 9.74426851916 4.98337330199 green false

7.63836147698 7.61050092554 7.24533208254 violet true

 

SAMPLE OUTPUT

The area is 20.14

The perimeter is 21.68

Triangle: side1 = 5.23 side2 = 8.64 side3 = 7.81

The area is 12.33

The perimeter is 16.47

Triangle: side1 = 4.74 side2 = 5.29 side3 = 6.44

The area is 18.38

The perimeter is 22.41

Triangle: side1 = 9.85 side2 = 7.66 side3 = 4.89

The area is 13.66

The perimeter is 21.01

Triangle: side1 = 6.28 side2 = 9.74 side3 = 4.98

The area is 24.30

The perimeter is 22.49

Triangle: side1 = 7.64 side2 = 7.61 side3 = 7.25

 

SAMPLE CODE
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for (int t = 0; t < T; t++) {
            double side1 = sc.nextDouble();
            double side2 = sc.nextDouble();
            double side3 = sc.nextDouble();
            GeometricObject triangle = new Triangle(side1, side2, side3);
            String color = sc.next();
            triangle.setColor(color);
            boolean filled = sc.nextBoolean();
            triangle.setFilled(filled);
            DecimalFormat df = new DecimalFormat("##.00");
            System.out.println("The area is " + df.format(triangle.getArea()));
            System.out.println("The perimeter is " + df.format(triangle.getPerimeter()));
            System.out.println(triangle);
        }
    }
}
abstract class GeometricObject {
    private String color = "white";
    private boolean filled;
    /**
     * Default construct
     */
    protected GeometricObject() {
    }
    /**
     * Construct a geometric object
     */
    protected GeometricObject(String color, boolean filled) {
        this.color = color;
        this.filled = filled;
    }
    /**
     * Getter method for color
     */
    public String getColor() {
        return color;
    }
    /**
     * Setter method for color
     */
    public void setColor(String color) {
        this.color = color;
    }
    /**
     * Getter method for filled. Since filled is boolean,
     * so, the get method name is isFilled
     */
    public boolean isFilled() {
        return filled;
    }
        /**
     * Setter method for filled
     */
    public void setFilled(boolean filled) {
        this.filled = filled;
    }

    /**
     * Abstract method findArea
     */
    public abstract double getArea();

    /**
     * Abstract method getPerimeter
     */
    public abstract double getPerimeter();
}
YOUR_CODE

 

class Triangle extends GeometricObject{
    private double side1, side2, side3;
    Triangle(){
        side1 = side2 = side3 = 1;
    }
    Triangle(double side1, double side2, double side3){
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }
    public double getArea(){
        double s = (side1 + side2 + side3) / 2;
        return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
    }
    public double getPerimeter(){
        return side1 + side2 + side3;
    }
    public String toString(){
        DecimalFormat df = new DecimalFormat("##.00");
        return "Triangle: side1 = " + df.format(side1) + " side2 = " + df.format(side2)+ " side3 = " + df.format(side3);
    }
}

 

반응형

댓글