package Calculator;
import java.util.regex.Pattern;
public class Parser {
private static final String OPERATION_REG = "[+\\-*/]";
private static final String NUMBER_REG = "^[0-9]*$";
private static AbstractOperation operation;
private static int firstNumber;
private static int secondNumber;
public static void setOperation(AbstractOperation operation) {
Parser.operation = operation;
}
public static double calculate(int firstNumber, int secondNumber) {
return Parser.operation.operate(Parser.firstNumber, Parser.secondNumber);
}
public Parser parseFirstNum(String firstInput) throws Exception{
if (!Pattern.matches(NUMBER_REG, firstInput)) {
throw new BadInputException("정수값");
}
this.firstNumber = Integer.parseInt(firstInput);
return this;
}
public Parser parseSecondNum(String secondInput) throws Exception {
if (!Pattern.matches(NUMBER_REG, secondInput)) {
throw new BadInputException("정수값");
}
this.secondNumber = Integer.parseInt(secondInput);
return this;
}
public Parser parseOperator(String operationInput) throws Exception {
if (!Pattern.matches(OPERATION_REG, operationInput)) {
throw new BadInputException("사칙 연산의 연산자");
}
switch (operationInput) {
case "+" -> Parser.setOperation(new AddOperation());
case "-" -> Parser.setOperation(new SubOperation());
case "*" -> Parser.setOperation(new MultiOperation());
case "/" -> Parser.setOperation(new DivOperation());
}
return this;
}
public double executeCalculator() {
return Parser.calculate(this.firstNumber, this.secondNumber);
}
}
package Calculator;
import java.util.Scanner;
public class CalculatorApp {
public static boolean start() throws Exception{
Parser parser = new Parser();
Scanner scanner = new Scanner(System.in);
System.out.println("첫번째 숫자를 입력해주세요!");
String firstInput = scanner.nextLine();
parser.parseFirstNum(firstInput);
System.out.println("연산자를 입력해주세요!");
String operator = scanner.nextLine();
parser.parseOperator(operator);
System.out.println("두번째 숫자를 입력해주세요!");
String secondInput = scanner.nextLine();
parser.parseSecondNum(secondInput);
System.out.println("연산 결과 : " + parser.executeCalculator());
return true;
}
}
public void parseFirstNum(String firstInput) throws Exception{
if (!Pattern.matches(NUMBER_REG, firstInput)) {
throw new BadInputException("정수값");
}
this.calculator.setFirstNumber(Integer.parseInt(firstInput));
return this;
}
이 코드에서 "Return value of the method is never used" 경고가 뜨는 것을 확인하였는데, 이러한 경고가 뜨는 이유는 parseFirstNum()메소드가 this를 반환하고 있지만, 해당 반환값을 변수에 저장하거나 메소드 호출의 인자로 전달하지 않고 있어서 이 경고가 나타나고 있다.
→ this에 대한 이해도가 더 필요해 보인다.