본문 바로가기
TIL

01/08(월) 내일배움캠프 Java 11일차 TIL - 계산기만들기

by 감자개발꾼 2024. 1. 8.

 

 

📖  오늘의 학습 키워드

  • 계산기

 

🥔  Step 1

Calculator Class 만들기

 

public class Calculator {

    public double calculate(String operator, int firstNumber, int secondNumber) {
        double answer = 0;

        if(operator.equals("+")){
            answer = firstNumber + secondNumber;
        }else if(operator.equals("-")){
            answer = firstNumber - secondNumber;
        }else if(operator.equals("*")){
            answer = firstNumber * secondNumber;
        }else if(operator.equals("/")){
            answer = firstNumber / secondNumber;
        }

        return answer;
    }
}

 

Main Class 만들기

 

public class Main {
    public static void main(String[] args) {
        Calculator calculator  = new Calculator();
        System.out.println(calculator.calculate("+", 10, 20));
        System.out.println(calculator.calculate("*", 10, 20));
    }
}

 

 

🥔  Step 2

- 여러 클래스로 나누기

 

Calculator

 

public class Calculator {

    private AbstractOperation operation;

    public Calculator(AbstractOperation operation) {
        this.operation = operation;
    }

    public void setOperation(AbstractOperation operation) {
        this.operation = operation;
    }

    public double calculate(int firstNumber, int secondNumber) {
        double answer = 0;
        answer = operation.operate(firstNumber, secondNumber);
        return answer;
    }

}

 

AbstractOperation

 

public abstract class AbstractOperation {
    public abstract double operate(int firstNumber, int secondNumber);
}

 

AddOperation

 

public class AddOperation extends AbstractOperation{
    @Override
    public double operate(int firstNumber, int secondNumber){
        return firstNumber + secondNumber;
    }
}

 

SubstractOperation

 

public class SubstractOperation extends AbstractOperation{
    @Override
    public double operate(int firstNumber, int secondNumber){
        return firstNumber - secondNumber;
    }
}

 

MultiplyOperation

 

public class MultiplyOperation extends AbstractOperation{
    @Override
    public double operate(int firstNumber, int secondNumber){
        return firstNumber * secondNumber;
    }
}

 

DivideOperation

 

public class DivideOperation extends AbstractOperation{
    @Override
    public double operate(int firstNumber, int secondNumber){
        return firstNumber / secondNumber;
    }
}

 

Main

 

public class Main {
    public static void main(String[] args) {
        Calculator calculator  = new Calculator(new AddOperation());
        System.out.println(calculator.calculate(10, 20));
        calculator.setOperation(new MultiplyOperation());
        System.out.println(calculator.calculate(10,20));
    }
}

 

 

 

 

 

 

📚  오늘의 회고

오늘은 클래스를 활용하여 사칙연산이 가능한

계산기를 만들어 봤습니다.

 

클래스.. 어렵네요

자바.. 어렵네요