private static final String OPERATION_REG = "[+\\-*/]";
private static final String NUMBER_REG = "^[0-9]*$";
자바 4주차 강의를 공부하고 난뒤 기존에 강의 3주차에서 과제로 풀었던 계산기 예제의 코드를 바꾸는 과제가 있었다.
예외처리를 통해 예상범위 밖의 값에 대해 예외를 던지고 기존 main함수에서 new 를 통해 연산자를 정해주었던에서 사용자입력으로 연산자를 정하는 변화에 대해 코드를 작성해야했다.
1. 예외 처리
우선 예외처리를 위한 정수와 연산자의 범위를 정규식을 통해 표현하였다.
private static final String OPERATION_REG = "[+\\-*/]";
private static final String NUMBER_REG = "^[0-9]*$";
그리고 Pattern.matches()메소드를 통해 정규식 범위내에 포함되는지 검사하고 범위 밖이라면 예외를 던진다.
if(!Pattern.matches(NUMBER_REG, firstInput))
throw new BadInputException("올바른 정수");
그리고 main에서 try - catch문을 통해 예외처리를 한다.
public class Main {
public static void main(String[] args) throws BadInputException {
boolean calculateEnded = false;
// 구현 2.
while(!calculateEnded){
try {
calculateEnded = CalculatorApp.start();
}catch (Exception e) {
String msg = e.getMessage();
System.out.println(msg);
}
}
}
}
이로써 예상범위외의 입력값에 대한 예외처리를 하였다
2. 연산자 사용자 입력을 통한 연산자 설정
기존 코드에서는 new AddOperator같이 직접 연산자 인스턴스를 만들어서 연산자를 정해주었지만 이번 과제에서는 사용자 입력을 통해 설정해주어야한다.
public Parser parseOperator(String operationInput) throws Exception{
// 구현 1.
if(!Pattern.matches(OPERATION_REG,operationInput))
throw new Exception("올바른 연산자");
switch (operationInput) {
case "+":
this.calculator.setOperation(new AddOperation());
break;
case "-":
this.calculator.setOperation(new SubOperation());
break;
case "*":
this.calculator.setOperation(new MulOperation());
break;
case "/":
this.calculator.setOperation(new DivOperation());
break;
}
return this;
}
위 코드는 우선 +, -, *, / 외의 입력을 받으면 예외를 던지고 정확한 연산자를 받았다면 입력받은 연산자에 따라 연산자 인스턴스를 생성해 Calculator 의 setOperation을 통해 연산자를 설정해준다.
'언어 > JAVA' 카테고리의 다른 글
| [TIL]20230810 - parallelStream() 도입 (0) | 2023.08.12 |
|---|---|
| [TIL]20230722 - 빌더 패턴 (0) | 2023.07.24 |
| [TIL]20230620 - 상속과 다형성 (0) | 2023.06.21 |
| [TIL]20230615 - 스트림의 toList()가 없다 (2) | 2023.06.16 |
| [TIL]20230613 - HashSet 의 저장방법 (0) | 2023.06.14 |