-
Notifications
You must be signed in to change notification settings - Fork 151
[4기 - 한승원] 1~2주차 과제 : 계산기 구현 미션 제출합니다(사칙연산) #168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: seungwon
Are you sure you want to change the base?
Changes from 11 commits
2f8bb46
5a6deed
c4c3e88
e2dcb42
bd3aee3
52a1300
ee4d032
842467d
c9c80e0
25a513e
6d94091
4d764ca
882c684
1a150a5
a3901a5
451742e
775466d
5e41f40
2590e8c
6b66bc0
2f88ba9
f154103
ddc919c
9b34581
9b943b9
c6c5a68
6d43a13
97b393a
84540a2
eeb3796
c37cdad
50cabb1
0ac007e
8b4ec3a
a3544d8
ea158fe
6f1519d
7fe46d5
aa52739
202ce5d
716fb12
c2351bd
1f42c10
358117c
f635ecb
06b76d3
84ff197
49675ef
62afa70
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package co.programmers.application; | ||
|
|
||
| import co.programmers.view.CalculatorInputView; | ||
| import co.programmers.view.CalculatorOutputView; | ||
| import co.programmers.view.InputView; | ||
| import co.programmers.view.OutputView; | ||
|
|
||
| public class Application { | ||
|
|
||
| public static void main(String[] args) { | ||
| InputView inputView = new CalculatorInputView(); | ||
| OutputView outputView = new CalculatorOutputView(); | ||
| Calculator calculator = new Calculator(inputView, outputView); | ||
| calculator.run(); | ||
| } | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 마지막 라인이 빠져있네요 |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package co.programmers.application; | ||
|
|
||
| import co.programmers.domain.Operator; | ||
| import co.programmers.domain.UserMenu; | ||
| import co.programmers.view.InputView; | ||
| import co.programmers.view.OutputView; | ||
| import java.util.Stack; | ||
|
|
||
| public class Calculator { | ||
|
|
||
| private final InputView inputView; | ||
| private final OutputView outputView; | ||
|
|
||
| public Calculator(InputView inputView, OutputView outputView) { | ||
| this.inputView = inputView; | ||
| this.outputView = outputView; | ||
| } | ||
|
|
||
| public void run() { | ||
| while (true) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 무한 루프보다는 탈출 조건이 명시 되어 있는 편이 좋은 거 같아요 |
||
| UserMenu userMenu = UserMenu.get(inputView.inputUserMenu()); | ||
| switch (userMenu) { | ||
| case INQUIRY: | ||
| // 구현 예정 | ||
| break; | ||
| case CALCULATE: | ||
| String expression = inputView.inputExpression(); | ||
| Integer output = calculate(expression); | ||
| outputView.print(String.valueOf(output)); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. valueOf 함수가 불필요하게 너무 반복되는 거 같아요.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. outputView를 수정하도록 하겠습니다 |
||
| break; | ||
| case TERMINATE: | ||
| return; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private Integer calculate(String input) { | ||
| char[] expression = input.toCharArray(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 입력 값이 아무 이상없이 들어올거라고 단정짓기에는 사용자의 입력이 너무 자유롭지 않을까요>
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. validation 관련해 추가하겠습니다 |
||
| Stack<Integer> Operands = new Stack<>(); | ||
| Stack<Character> Operators = new Stack<>(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 계산을 매번 할 때마다 새로운 Stack을 만들게 되겠네요! 비효율적이지 않을까요? |
||
| for (int i = 0; i < expression.length; i++) { | ||
| if (Character.isWhitespace(expression[i])) { | ||
| continue; | ||
| } | ||
| if (Character.isDigit(expression[i])) { | ||
| StringBuffer operand = new StringBuffer(); | ||
| while (i < expression.length && Character.isDigit(expression[i])) { | ||
| operand.append(expression[i++]); | ||
| } | ||
| i--; | ||
| Operands.push(Integer.parseInt(operand.toString())); | ||
| } else if (expression[i] == '(') { | ||
| Operators.push(expression[i]); | ||
| } else if (expression[i] == ')') { | ||
| evaluateOperators(Operands, Operators); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. bracket은 후순위로 진행해주시면 될 것 같아요
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 우선은 삭제했습니다 |
||
| } else { | ||
| while (!Operators.empty() && comparePriority(expression[i], Operators.peek())) { | ||
| Operands.push(Operator.calculate( | ||
| String.valueOf(Operators.pop()), Operands.pop(), Operands.pop() | ||
| )); | ||
| } | ||
| Operators.push(expression[i]); | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 기능에 비해 로직이 너무 복잡한 것 같아요
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 넵 계산 관련 로직도 수정하고 그에 따라 메소드도 분리해보았습니다(Calculation 클래스 확인 부탁드려요). |
||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 로직이 굉장히 복잡하고 요구사항과 강하게 결합되어 있어요. 추가적으로 객체지향 생활체조 원칙을 따라 2 depth 이상 코드를 들여쓰지 말고, else와 else if를 사용하지 않고 리팩토링 하면 좀 더 가독성 있는 코드를 짤 수 있을 것 같아요. |
||
| evaluateOperators(Operands, Operators); | ||
| return Operands.pop(); | ||
| } | ||
|
|
||
| private void evaluateOperators(Stack<Integer> operands, Stack<Character> operators) { | ||
| while (!operators.empty() && (operators.peek() != '(')) { | ||
| Character operator = operators.pop(); | ||
| Integer operand1 = operands.pop(); | ||
| Integer operand2 = operands.pop(); | ||
| int result = Operator.calculate( | ||
| String.valueOf(operator), operand1, operand2 | ||
| ); | ||
| operands.push(result); | ||
| } | ||
|
|
||
| if (!operators.empty()) { | ||
| operators.pop(); | ||
| } | ||
| } | ||
|
|
||
| private boolean comparePriority(char operator1, char operator2) { | ||
| return Operator.getSymbol(String.valueOf(operator1)).getPriority() >= | ||
| Operator.getSymbol(String.valueOf(operator2)).getPriority(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 우선순위를 비교하는 책임은 Operator에 있어도 되지 않을까요?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Operator 내에도 우선순위(priority) 필드를 가져서 해당 값을 사용하는 로직을 변경하겠습니다.. |
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,60 @@ | ||||||||||||||||||||||
| package co.programmers.domain; | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| import co.programmers.exception.ExceptionMessage; | ||||||||||||||||||||||
| import java.util.Collections; | ||||||||||||||||||||||
| import java.util.Map; | ||||||||||||||||||||||
| import java.util.Optional; | ||||||||||||||||||||||
| import java.util.function.BiFunction; | ||||||||||||||||||||||
| import java.util.function.Function; | ||||||||||||||||||||||
| import java.util.stream.Collectors; | ||||||||||||||||||||||
| import java.util.stream.Stream; | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| public enum Operator { | ||||||||||||||||||||||
| ADDITION("+", 2, (operand1, operand2) -> Integer.valueOf( | ||||||||||||||||||||||
| operand1 + operand2 | ||||||||||||||||||||||
| )), | ||||||||||||||||||||||
| SUBTRACTION("-", 2, (operand1, operand2) -> Integer.valueOf( | ||||||||||||||||||||||
| operand2 - operand1 | ||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 인자값이 모두 Integer인데 Integer.valueOf를 사용하는 이유가 있을까요? |
||||||||||||||||||||||
| )), | ||||||||||||||||||||||
| MULTIPLICATION("*", 1, (operand1, operand2) -> Integer.valueOf( | ||||||||||||||||||||||
| operand1 * operand2 | ||||||||||||||||||||||
| )), | ||||||||||||||||||||||
| DIVISION("/", 1, (operand1, operand2) -> { | ||||||||||||||||||||||
| if (operand2 == 0) { | ||||||||||||||||||||||
| throw new IllegalArgumentException(ExceptionMessage.DIVIDED_BY_ZERO); | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| return Integer.valueOf(operand1 / operand2); | ||||||||||||||||||||||
| }), | ||||||||||||||||||||||
| OPENED_PARENTHESIS("(", 3, (operand1, operand2) -> 0), | ||||||||||||||||||||||
| CLOSED_PARENTHESIS(")", 3, (operand1, operand2) -> 0); | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| private static final Map<String, Operator> operators = | ||||||||||||||||||||||
| Collections.unmodifiableMap(Stream.of(values()) | ||||||||||||||||||||||
| .collect(Collectors.toMap(Operator::getSymbol, Function.identity()))); | ||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 해당 Map의 쓰임새가 좀 더 명시적으로 표현 될 수 있으면 좋을 것 같아요. |
||||||||||||||||||||||
| private final String symbol; | ||||||||||||||||||||||
| private final int priority; | ||||||||||||||||||||||
| private final BiFunction<Integer, Integer, Integer> operation; | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| Operator(String symbol, int priority, BiFunction<Integer, Integer, Integer> operation) { | ||||||||||||||||||||||
| this.symbol = symbol; | ||||||||||||||||||||||
| this.priority = priority; | ||||||||||||||||||||||
| this.operation = operation; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| public static Integer calculate(String operator, Integer operand1, Integer operand2) { | ||||||||||||||||||||||
| return getSymbol(operator).operation.apply(operand1, operand2); | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| public static Operator getSymbol(String operator) { | ||||||||||||||||||||||
| return Optional.ofNullable(operators.get(operator)) | ||||||||||||||||||||||
| .orElseThrow(() -> new IllegalArgumentException(ExceptionMessage.INVALID_SYMBOL)); | ||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 여기서 굳이 optional 로 한 번 감싸줘야할까요?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. operators.get()함수의 반환값이 null이 될 수 있어서(입력한 operator 가 정의된 +,-,*,/에 해당되지 않는 다면) exception처리를 하기 위해 위처럼 작성 했습니다. 다만 Optional로도 감싸주고 exception도 날리는건 중복으로 처리하는 것 같아서 둘중에 하나로만 했어도 될 것 같습니다. 아래는 optional에 대해 제가 찾아보고 이해한 내용입니다. Optional은 호출 하는 쪽에 '반환 값이 null일 수도 있다(반환할 결과값이 없다)' 라고 명시적으로 알려주는 역할을 가진 것으로 이해했습니다. 그러니까 메서드가 반환한 결과 값이 '없음'을 표현하고자 하는데 null을 반환하는 것은 에러를 유발하거나 해서는 안되는 행동으로 여겨지니 도입된 개념입니다. 호출하는 쪽에서 null 체크를 쉽게 할 수 있어 NullPointerException을 방지할 수 있습니다. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 여기는 잘 고민해보고 더 궁금한 내용이 있으면 언제든 말씀해주세요~ |
||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
이런 방법은 어떠신가요? |
||||||||||||||||||||||
|
|
||||||||||||||||||||||
| private String getSymbol() { | ||||||||||||||||||||||
| return symbol; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| public int getPriority() { | ||||||||||||||||||||||
| return priority; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package co.programmers.domain; | ||
|
|
||
| import java.util.Collections; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.function.Function; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.Stream; | ||
|
|
||
| public enum UserMenu { | ||
| INQUIRY("1"), | ||
| CALCULATE("2"), | ||
| TERMINATE("3"); | ||
|
|
||
| private static final Map<String, UserMenu> values = | ||
| Collections.unmodifiableMap(Stream.of(values()) | ||
| .collect(Collectors.toMap(UserMenu::getValue, Function.identity()))); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. values라는 이름은 해당 자료구조가 어떤 역할을 하는지 알아보기 어려워요.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 위와 같은 이유로 삭제했습니다 |
||
| private final String value; | ||
|
|
||
| UserMenu(String value) { | ||
| this.value = value; | ||
| } | ||
|
|
||
| public static UserMenu get(String input) { | ||
| return Optional.ofNullable(values.get(input)).orElse(TERMINATE); | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 어떤 의도로 Optional을 사용하신 걸까요? |
||
|
|
||
| public String getValue() { | ||
| return value; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package co.programmers.exception; | ||
|
|
||
| public class ExceptionMessage { | ||
|
|
||
| public static final String DIVIDED_BY_ZERO = "0으로 나눌 수 없습니다."; | ||
| public static final String INVALID_SYMBOL = "잘못된 연산 기호입니다."; | ||
| public static final String INVALID_INPUT = "잘못된 입력입니다"; | ||
|
|
||
| private ExceptionMessage() { | ||
| } | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 메시지 관리를 하는 방법에는 어떤것들이 있을까요?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. enum을 사용해 에러코드와 함께 관리하거나 Exception 클래스를 상속받은 클래스를 구현할 수도 있을 것 같습니다. 다만 저는 개수가 그렇게 많지 않고 단순히 에러 메시지를 코드화하여 관리하기 위함이라 위와 같이 사용했습니다. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 개발하면서 그 어떤것도 확답을 내릴 수 없어요 갑자기 변경 할 때 전체적인 구조가 흔들리는 것 보단 지금은 괜찮더라도 추후 변경을 고려하여 설계하는 연습도 필요해요
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 추후 변경을 고려하여 설계하라는 점은 염두에 두겠습니다🤩 그런데 예외메시지만 관리한다는 관점에서 볼때 enum을 사용하는 것과 현재방법의 차이를 잘 모르겠습니다,, 그리고 Exception 클래스를 상속받은 사용자 정의 예외클래스를 구현하는 것은 현재 예외의 개수도 적고 표준예외로 충분히 표현 가능하다고 느껴지는데 과한 구현이지 않을까 싶어서 필요하다면 나중에 확장하면서 고려하면 되지않을까 싶은데... 어떨까요....?🥹 제가 놓치고 있는 부분이 있을까요? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
제가 이 클래스를 작성했다고 생각해보면 당장 위 고민들이 떠오르네요 |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| package co.programmers.view; | ||
|
|
||
| import co.programmers.exception.ExceptionMessage; | ||
| import co.programmers.domain.UserMenu; | ||
| import java.util.Arrays; | ||
| import java.util.Scanner; | ||
| import java.util.Set; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class CalculatorInputView implements InputView { | ||
|
|
||
| private static final Scanner SCANNER = new Scanner(System.in); | ||
| private static final Set<String> USER_MENU = | ||
| Arrays.stream(UserMenu.values()) | ||
| .map(UserMenu::getValue) | ||
| .collect(Collectors.toSet()); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. UserMenu Enum이 있음에도 불구하고 Set을 사용하신 이유가 궁금해요. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. InputView에서 UserMenu의 유효성을 검사하고 있는 부분이 좀 어색하게 보였어요. |
||
|
|
||
| public CalculatorInputView() { | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 빈생성자는 의도하신걸까요?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 빠뜨리고 수정한 것 같습니다. 삭제하겠습니다 |
||
|
|
||
| public String inputUserMenu() { | ||
| printMenuChoiceGuide(); | ||
| String userInput = SCANNER.next(); | ||
| SCANNER.nextLine(); | ||
| try { | ||
| validateUserMenuChoice(String.valueOf(userInput)); | ||
| } catch (IllegalArgumentException illegalArgumentException) { | ||
| System.out.println(illegalArgumentException.getMessage()); | ||
| return UserMenu.TERMINATE.getValue(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. UserMenu는 사용자가 입력값으로 기대할 수 있는 선택지 중 하나라고 생각해요. |
||
| } | ||
| return userInput; | ||
| } | ||
|
|
||
| public String inputExpression() { | ||
| printCalculationGuide(); | ||
| String expression = SCANNER.nextLine(); | ||
| return expression; | ||
| } | ||
|
|
||
| private void printCalculationGuide() { | ||
| System.out.println("1 + 2 * 3와 같은 형식으로 계산하고자 하는 식을 입력하세요."); | ||
| System.out.print("> "); | ||
| } | ||
|
|
||
| private void printMenuChoiceGuide() { | ||
| System.out.println("\n[다음 중 원하시는 항목을 숫자로 입력하세요]"); | ||
| System.out.println("1. 조회"); | ||
| System.out.println("2. 계산"); | ||
| System.out.println("3. 종료"); | ||
| System.out.print("> 선택 : "); | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. inputView에서 Output을 진행하고 있네요!
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. outputView클래스로 이동하여 수정하겠습니다 |
||
|
|
||
| private void validateUserMenuChoice(String userInput) throws IllegalArgumentException { | ||
| if (!USER_MENU.contains(userInput)) { | ||
| throw new IllegalArgumentException(ExceptionMessage.INVALID_INPUT); | ||
| } | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. contains 메소드를 사용하는 것도 좋지만, enum을 좀 더 잘 활용하려면 Menu를 검증하는 메소드를 직접 만드는 것도 좋아보여요.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. enum클래스 내에 메소드를 만들어서 사용하라는 말씀이실까요? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 넵! 아래의 코멘트 참고하시면 될 것 같습니다 |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| package co.programmers.view; | ||
|
|
||
| public class CalculatorOutputView implements OutputView { | ||
|
|
||
| public void print(String content) { | ||
| System.out.println(">> 결과 : " + content); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| package co.programmers.view; | ||
|
|
||
| public interface InputView { | ||
|
|
||
| String inputUserMenu(); | ||
|
|
||
| String inputExpression(); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package co.programmers.view; | ||
|
|
||
| public interface OutputView { | ||
|
|
||
| void print(String content); | ||
|
|
||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍