-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCalculator.java
More file actions
55 lines (40 loc) · 1.43 KB
/
Calculator.java
File metadata and controls
55 lines (40 loc) · 1.43 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
package calculator;
import java.util.*;
// 연산 책임
public class Calculator {
private int result = 0;
public int calculate(ArrayList<String> inputArrayList) {
// 단일 원소인 경우 그대로 return
if (isSingleElement(inputArrayList)) {
return Integer.parseInt(inputArrayList.get(0));
}
// 큐 선언
LinkedList<String> stringQueue = toQueue(inputArrayList);
while (stringQueue.size() > 1) {
result = operate(
stringQueue.poll(),
stringQueue.poll(),
stringQueue.poll()
);
stringQueue.addFirst(String.valueOf(result));
}
return result;
}
private boolean isSingleElement(ArrayList<String> inputArrayList) {
return inputArrayList.size() == 1;
}
private LinkedList<String> toQueue(ArrayList<String> inputArrayList) {
return new LinkedList<>(inputArrayList);
}
private int operate(String num1String, String operator, String num2String) {
int num1 = Integer.parseInt(num1String);
int num2 = Integer.parseInt(num2String);
return switch (operator) {
case "+" -> num1 + num2;
case "-" -> num1 - num2;
case "*" -> num1 * num2;
case "/" -> num1 / num2;
default -> throw new IllegalStateException("Unexpected value: " + operator);
};
}
}