Anna belly belly hard/java_spring

P1_C3_4. 사칙연산 계산기 구현

bibiana 각선행 2023. 5. 14. 15:05
반응형

<요구사항>
• 간단한 사칙연산을 할 수 있다.
• 양수로만 계산할 수 있다.
• 나눗셈에서 0을 나누는 경우 IllegalArgument 예외를 발생시킨다.
• MVC패턴(Model-View-Controller) 기반으로 구현한다.

 

 

 

control(comand)+alt(option)+l ;자동정렬

 

 

 

 

 

테스트 코드를 하나로

 

enum 만들어줌.

package org.example.Calculator;
import java.util.Arrays;

public enum ArithmeticOperator {
    ADDITION("+") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 + operand2;
        }
    }, SUBTRACTION("-") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 - operand2;
        }
    }, MULTIPLICATION("*") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 * operand2;
        }
    }, DIVISION("/") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 / operand2;
        }
    };
    private final String operator;

    ArithmeticOperator(String operator) {
        this.operator = operator;
    }


    public abstract int arithmeticCalculate(final int operand1, final int operand2);


    // 외부 노출되는 public interface
    public static int calculate(int operand1, String operator, int operand2) {
        ArithmeticOperator arithmeticOperator = Arrays.stream(values())
                                                      .filter(v -> v.operator.equals(operator))
                                                      .findFirst()
                                                      .orElseThrow(() -> new IllegalArgumentException("올바른 사칙연산이 아닙니다."));

        return arithmeticOperator.arithmeticCalculate(operand1,operand2);
    }
}

test 성공! 리팩토링 성공!

반응형