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

Chapter 9. Objects and Classes[Java Basic]

by sonpang 2021. 11. 6.
반응형

9.A - Rectangle 클래스

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

다음 특징을 가지는 Rectangle 클래스를 만들기 바랍니다.

double 형의 width와 height를 필드로 가진다.

인자가 없는 생성자와 width와 height를 인자로 가지는 생성자를 가진다.

getArea() 메소드는 사각형의 넓이를 리턴한다.

getPerimeter() 메소드는 사각형의 둘레를 리턴한다.

여러분이 작성한 코드는 아래 샘플코드의 YOUR_CODE 부분에 들어가 컴파일 됩니다.

 

(The Rectangle class) Following the example of the Circle class in Section 9.2, design a class named Rectangle to represent a rectangle. The class contains:

Two double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height.

A no-arg constructor that creates a default rectangle.

A constructor that creates a rectangle with the specified width and height.

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

A method named getPerimeter() that returns the perimeter.

Your code is compiled into the YOUR_CODE part of the sample code below

 

INPUT

* Line 1 : 사각형의 너비 (1~1,000 범위의 실수)

* Line 2 : 사각형의 높이 (1~1,000 범위의 실수)

 

OUTPUT

* Line 1 : 사각형의 넓이 (소수점 둘째 자리로 반올림)

* Line 2 : 사각형의 둘레 (소수점 둘째 자리로 반올림)

 

SAMPLE CODE

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

        double w1, h1;
        w1 = sc.nextDouble();
        h1 = sc.nextDouble();

        Rectangle r1 = new Rectangle();
        r1.width = w1;
        r1.height = h1;
        System.out.printf("%.2f\n", r1.getArea());

        Rectangle r2 = new Rectangle(w1, h1);
        System.out.printf("%.2f\n", r2.getPerimeter());
    }
}

 

YOUR_CODE

 

SAMPLE INPUT

2

3

 

SAMPLE OUTPUT

6.00

10.00

 

 

class Rectangle{
    double width;
    double height;
    public Rectangle(){
 
    }
    public Rectangle(double w, double h){
        width = w;
        height = h;
    }
    public double getArea(){
        return width * height;
    }
    public double getPerimeter() {
        return (width + height) * 2;
    }
}

 

 

9.B - Stock 클래스

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

여러분은 다음과 같은 특징을 가지는 Stock 클래스를 만들어야 합니다.

id와 name 필드를 가진다.

전날의 주식값을 저장하는 double형의 previousClosingPrice 필드를 가진다.

오늘의 주식값을 저장하는 double형의 currentPrice 필드를 가진다.

id와 name을 통해서 클래스를 생성할 수 있어야 한다.

주식값의 변화량을 %로 표시하는 getChangePercent 메소드를 가진다.

여러분이 작성한 코드는 아래 샘플코드의 YOUR_CODE 부분에 들어가 컴파일 됩니다.

(The Stock class) Following the example of the Circle class in Section 9.2, design a class named Stock that contains:

■ A string data field named symbol for the stock’s symbol.

■ A string data field named name for the stock’s name.

■ A double data field named previousClosingPrice that stores the stock price for the previous day.

■ A double data field named currentPrice that stores the stock price for the current time.

■ A constructor that creates a stock with the specified symbol and name.

■ A method named getChangePercent() that returns the percentage changed from previousClosingPrice to currentPrice.

 

INPUT

* Line 1 : id 문자열 (최대길이1,000)

* Line 2 : name 문자열 (최대길이1,000)

* Line 3 : 전날의 주식값 (1~1,000,000,000 사이의 실수)

* Line 4 : 오늘의 주식값 (1~1,000,000,000 사이의 실수)

 

OUTPUT

* Line 1~3 : 샘플 출력 참조

 

SAMPLE CODE

import java.util.*;

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

        Stock stock = new Stock(sc.nextLine(), sc.nextLine());
        stock.setPreviousClosingPrice(sc.nextDouble());
        stock.setCurrentPrice(sc.nextDouble());

        System.out.printf("Prev Price: %.2f\n", stock.getPreviousClosingPrice());
        System.out.printf("Curr Price: %.2f\n", stock.getCurrentPrice());
        System.out.printf("Price Change: %.2f%%\n", stock.getChangePercent() * 100);
    }
}

 

YOUR_CODE

 

SAMPLE INPUT

Naver

Naver Corp.

392930

29911223

 

SAMPLE OUTPUT

Prev Price: 392930.00

Curr Price: 29911223.00

Price Change: 7512.35%

 

class Stock{
    String id;
    String name;
    double pcp, cp;
    public Stock(String s1, String s2){
        String id = s1;
        String name = s2;
    }
    public void setPreviousClosingPrice(double price){
        pcp = price;
    }
    public void setCurrentPrice(double price){
        cp = price;
    }
    public double getPreviousClosingPrice(){
        return pcp;
    }
    public double getCurrentPrice(){
        return cp;
    }
    public double getChangePercent(){
        return (cp-pcp) / pcp;
    }
}

 

 

9.C - Date 클래스

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

UTC+0 시간대에서 1970년 1월 1일부터 A까지 총 몇 ms가 지났는지 주어집니다. 여러분은 Date 개체를 사용해서 한국에서 A의 날짜와 시간을 찾는 프로그램을 작성해야 합니다. 예를 들어 1000000000가 주어진다면 "Mon Jan 12 22:46:40 KST 1970"를 출력합니다.

(Use the Date class) Write a program that creates a Date object, sets its elapsed time to 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, and 100000000000, and displays the date and time using the toString() method, respectively.

 

INPUT

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

* Line 2 ~ T+1 : 밀리초를 나타내는 정수 (1~1,000,000,000,000,000)

 

OUTPUT

* Line 1 ~ T : 해당 날짜와 시간을 형식에 맞추어 출력

 

SAMPLE INPUT

3

1000000000

1000000000000

1000000000000000

 

SAMPLE OUTPUT

Mon Jan 12 22:46:40 KST 1970

Sun Sep 09 10:46:40 KST 2001

Fri Sep 27 10:46:40 KST 33658

 

import java.util.Date;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt(), i;
        long data[] = new long[n];
        Date date = new Date();
        for(i = 0; i < n; i++)
            data[i] = input.nextLong();
        for(i = 0; i < n; i++){
            date.setTime(data[i]);
            System.out.println(date.toString());
        }
 
    }
}
반응형

 

9.D - GregorianCalendar

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

날짜와 시간을 입력받아 +1000일을 한뒤 -1000초를 해서 계산된 날짜와 시간을 출력하는 프로그램을 작성하세요.

 

INPUT

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

* Line 2 ~ T+1 : 년 월 일 시 분 초 (공백으로 구분된 6개의 정수)

- 년의 범위는 1,000~3,000

- 월의 범위는 1~12

- 일의 범위는 1~31

- 시의 범위는 0~23

- 분과 초의 범위는 0~59

 

OUTPUT

* Line 1 ~ T : 년 월 일 시 분 초 (샘플 아웃풋 처럼 구분된 6개의 정수)

 

SAMPLE INPUT

3

1999 12 24 23 0 0

2000 1 1 1 0 0

2015 10 16 21 38 29

 

SAMPLE OUTPUT

2002.09.19 22:43:20

2002.09.27 00:43:20

2018.07.12 21:21:49

 

import java.util.Scanner;
import java.util.Calendar;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt(), i, data[][] = new int[n][6];
        Calendar date = Calendar.getInstance();
        for(i = 0; i < n; i++){
            data[i][0] = input.nextInt();
            data[i][1] = input.nextInt();
            data[i][2] = input.nextInt();
            data[i][3] = input.nextInt();
            data[i][4] = input.nextInt();
            data[i][5] = input.nextInt();
        }
        for(i = 0; i < n; i++){
            date.set(data[i][0], data[i][1] - 1 , data[i][2] + 1000, data[i][3], data[i][4], data[i][5] - 1000);
            System.out.format("%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS\n",date.getTime());
        }
    }
}

 

 

9.E - Account 클래스

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

다음 특징을 가지는 Account 클래스를 만들기 바랍니다.

int형의 id 필드를 가진다.

double형의 balance 필드를 가진다.

double형을 인자로 가지고 현재 이자율을 저장하는 annualInterestRate를 가진다. 모든 계좌는 같은 이자율을 가진다고 가정한다.

계좌가 만들어졌을 때 데이터를 저장하는 dateCreated 필드를 가진다.

계좌를 default로 만드는 무(無)인자(no-arg) 생성자를 가진다.

특정한 id와 초기 balance를 가진 계좌를 만드는 생성자를 가진다.

id와 balance, 연이자율에 대한 accessor 메소드(값을 반환하는 메소드)와 mutator 메소드(값을 변경시키는 메소드)를 가진다.

dateCreatead에 대한 accessor 메소드를 가진다.

월이자율을 반환하는 getMonthlyInterestRate() 메소드를 가진다.

월이자를 반환하는 getMonthlyInterest() 메소드를 가진다.

계좌에서 일정한 금액을 인출하는 withdraw 메소드를 가진다.

계좌에 일전한 금액을 입금하는 deposit 메소드를 가진다.

getMonthlyInterest () 메소드는 금리가 아닌 월간이자를 반환하는 것입니다. 월간이자는 잔액 * 월간 이자율입니다. monthlyInterestRate는 annualInterestRate / 12입니다. annualInterestRate는 백분율입니다 (예 : 4.5 %). 그것을 100으로 나눌 필요가 있습니다.

The class contains:

A private int data field named id for the account (default 0).

A private double data field named balance for the account (default 0).

A private double data field named annualInterestRate that stores the current interest rate (default 0). Assume all accounts have the same interest rate.

A private Date data field named dateCreated that stores the date when the account was created.

A no-arg constructor that creates a default account.

A constructor that creates an account with the specified id and initial balance.

The accessor and mutator methods for id, balance, and annualInterestRate.

The accessor method for dateCreated.

A method named getMonthlyInterestRate() that returns the monthly interest rate.

A method named getMonthlyInterest() that returns the monthly interest.

A method named withdraw that withdraws a specified amount from the account.

A method named deposit that deposits a specified amount to the account.

The method getMonthlyInterest() is to return monthly interest, not the interest rate. Monthly interest is balance * monthlyInterestRate. monthlyInterestRate is annualInterestRate / 12. Note that annualInterestRate is a percentage, e.g., like 4.5%. You need to divide it by 100.

여러분이 작성한 코드는 아래 샘플코드의 YOUR_CODE 부분에 들어가 컴파일 됩니다.

 

INPUT 샘플 코드 참조

 

OUTPUT 샘플 코드 참조

- 출금 금액이 잔액 보다 클경우 출금하지 않는다.

 

SAMPLE INPUT

1

1000

10

20000

100

 

SAMPLE OUTPUT

Balance : 1000.00

Monthly interest : 8.33

Balance : 1000.00

Monthly interest : 8.33

Balance : 1100.00

Monthly interest : 9.17

 

SAMPLE CODE

import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Account account = new Account(sc.nextInt(), sc.nextInt());
        Account.setAnnualInterestRate(sc.nextDouble());
        System.out.printf("Balance : %.2f\n", account.getBalance());
        System.out.printf("Monthly interest : %.2f\n", account.getMonthlyInterest());
        account.withdraw(sc.nextDouble());
        System.out.printf("Balance : %.2f\n", account.getBalance());
        System.out.printf("Monthly interest : %.2f\n", account.getMonthlyInterest());
        account.deposit(sc.nextDouble());
        System.out.printf("Balance : %.2f\n", account.getBalance());
        System.out.printf("Monthly interest : %.2f\n", account.getMonthlyInterest());
    }
}

 

YOUR_CODE

 

class Account{
    private static int id;
    private static double balance;
    private static double aIR;
    private static Date dC;
    public Account(int inputid, double inputbalance ){
        id = inputid;
        balance = inputbalance;
    }
    public Account(){
 
    }
    public static void setAnnualInterestRate(double inputaIR){
        aIR = inputaIR;
    }
    public static double getBalance(){
        return balance;
    }
    public static double getMonthlyInterestRate(){
        return aIR / 1200;
    }
    public static double getMonthlyInterest(){
        return (aIR / 1200) * balance;
    }
    public static void deposit(double input){
        balance += input;
    }
    public static void withdraw(double output){
        if(output > balance)
            return;
        balance -= output;
    }
}

 

 

9.F - Fan1 클래스

Time Limit: 1s Memory Limit: 128MB

 

DESCRIPTION

다음 특징을 가지는 Fan1 클래스를 만들기 바랍니다.

선풍기 속도를 나타내는 상수 SLOW, MEDIUM, FAST를 가지고, 그 값은 각각 1, 2, 3이다.

선풍기의 속도를 나타내는 int형의 speed 필드를 가진다. (기본은 SLOW)

선풍기 전원의 상태를 나타내는 boolean형의 on 필드를 가진다. (기본은 false)

선풍기의 반지름을 나타내는 double형의 radius 필드를 가진다. (기본은 5)

선풍기의 색상을 나타내는 string형의 color 필드를 가진다. (기본은 blue)

모든 데이터 필드에 대한 accessor 메소드와 mutator 메소드를 가진다.

기본값의 가지고 있는 선풍기를 생성하는 무(無)인자(no-arg) 생성자를 가진다.

선풍기의 특징을 반환하는 toString() 메소드를 가진다. 만약 선풍기가 켜져있다면 이 메소드는 선풍기의 속도, 색상, 반지름을 하나의 string으로 반환한다. 선풍기가 꺼져있다면, 선풍기의 색상, 반지름과 "fan is off"라는 string을 하나의 string으로 반환한다.

The class contains:

Three constants named SLOW, MEDIUM, and FAST with the values 1, 2, and 3 to denote the fan speed.

A private int data field named speed that specifies the speed of the fan (the default is SLOW).

A private boolean data field named on that specifies whether the fan is on (the default is false).

A private double data field named radius that specifies the radius of the fan (the default is 5).

A string data field named color that specifies the color of the fan (the default is blue).

The accessor and mutator methods for all four data fields.

A no-arg constructor that creates a default fan.

A method named toString() that returns a string description for the fan. If the fan is on, the method returns the fan speed, color, and radius in one combined string. If the fan is not on, the method returns the fan color and radius along with the string “fan is off” in one combined string.

 

INPUT 샘플 코드 참조

 

OUTPUT 샘플 코드 참조 - 실수형은 소수점 둘째자리로 반올림

 

SAMPLE CODE

import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        Fan1 fan1 = new Fan1();
        for (int i = 0; i < n; i++) {
            String op = sc.next();
            String val = sc.next();
            if (op.compareTo("speed") == 0) {
                if (val.compareTo("SLOW") == 0) fan1.setSpeed(Fan1.SLOW);
                else if (val.compareTo("FAST") == 0) fan1.setSpeed(Fan1.FAST);
                else fan1.setSpeed(Fan1.MEDIUM);
            } else if (op.compareTo("radius") == 0) {
                fan1.setRadius(Double.parseDouble(val));
            } else if (op.compareTo("color") == 0) {
                fan1.setColor(val);
            } else if (op.compareTo("on") == 0) {
                if (val.compareTo("true") == 0) fan1.setOn(true);
                else fan1.setOn(false);
            }
        }
        System.out.println(fan1.toString());
    }
}

 

SAMPLE INPUT

2

speed FAST

on true

 

SAMPLE OUTPUT

speed 3

color blue

radius 5.00

 

class Fan1{
    static final int SLOW = 1, MEDIUM = 2, FAST = 3;
    static int speed;
    static boolean on;
    static double radius;
    static String color;
    Fan1(){
        speed = SLOW;
        on = false;
        radius = 5;
        color = "blue";
    }
    public void setSpeed(int inputspeed){
        Fan1.speed = inputspeed;
    }
    public void setRadius(double inputradius){
        Fan1.radius = inputradius;
    }
    public void setColor(String inputcolor){
        Fan1.color = inputcolor;
    }
    public void setOn(boolean inputon){
        Fan1.on = inputon;
    }
    public String toString(){
        String output = "";
        String radius = String.format("%.2f",Fan1.radius);
        if(Fan1.on == true){
            output += "speed " + Fan1.speed;
            output += "\ncolor " + Fan1.color;
            output += "\nradius " + radius;
        }
        else{
            output += "color " + Fan1.color;
            output += "\nradius " + radius;
            output += "\nfan is off";
        }
        return output;
    }
}

 

Wrong Answer 0
class Fan1{
    static final int SLOW = 1, MEDIUM = 2, FAST = 3;
    static int speed;
    static boolean on;
    static double radius;
    static String color;
    Fan1(){
        speed = SLOW;
        on = false;
        radius = 5;
        color = "blue";
    }
    public void setSpeed(int inputspeed){
        Fan1.speed = inputspeed;
    }
    public void setRadius(double inputradius){
        Fan1.radius = inputradius;
    }
    public void setColor(String inputcolor){
        Fan1.color = inputcolor;
    }
    public void setOn(boolean inputon){
        Fan1.on = inputon;
    }
    public String toString(){
        String output = "";
        String radius = String.format("%.2f",Fan1.radius);
        if(Fan1.on == true){
            output += "speed " + Fan1.speed;
            output += "\ncolor " + Fan1.color;
            output += "\nradius " + radius;
        }
        else{
            output += "speeed " + Fan1.color;
            output += "\ncolor " + radius;
            output += "\nfan is off";
        }
        return output;
    }
}

 

반응형

댓글