-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathCalculator.java
More file actions
89 lines (80 loc) · 3.13 KB
/
Calculator.java
File metadata and controls
89 lines (80 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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) {
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));
break;
case TERMINATE:
return;
}
}
}
private Integer calculate(String input) {
char[] expression = input.toCharArray();
Stack<Integer> Operands = new Stack<>();
Stack<Character> Operators = new 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);
} 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]);
}
}
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();
}
}