📖 오늘의 학습 키워드
- 계산기
🥔 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));
}
}
📚 오늘의 회고
오늘은 클래스를 활용하여 사칙연산이 가능한
계산기를 만들어 봤습니다.
클래스.. 어렵네요
자바.. 어렵네요
'TIL' 카테고리의 다른 글
01/10(수) 내일배움캠프 Java 13일차 TIL - 키오스크 만들기 (0) | 2024.01.10 |
---|---|
01/09(화) 내일배움캠프 Java 12일차 TIL - 키오스크 만들기 (0) | 2024.01.09 |
01/05(금) 내일배움캠프 Java 10일차 TIL - 오버로딩, 오버라이딩 (0) | 2024.01.05 |
01/04(목) 내일배움캠프 Java 9일차 TIL - 객체 (0) | 2024.01.04 |
01/03(수) 내일배움캠프 Java 8일차 TIL - 배열, 컬렉션 (0) | 2024.01.03 |