forked from next-step/java-baseball-playground
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStringCalculator.java
More file actions
37 lines (28 loc) · 1.05 KB
/
StringCalculator.java
File metadata and controls
37 lines (28 loc) · 1.05 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
package calculaotor;
import java.util.*;
public class StringCalculator {
private static final String REGEX = " ";
private static final String DELIMITER = "*-+/";
private final Number result;
public StringCalculator(String expression) {
this.result = calculate(expression);
}
private Number calculate(String expression) {
String[] expressionSplit = expression.split(REGEX);
Deque<Delimiter> delimiter = new ArrayDeque<>();
Deque<Number> numbers = new ArrayDeque<>();
Arrays.stream(expressionSplit).forEach(s -> {
if (!DELIMITER.contains(s)) {
numbers.addLast(new Number(s));
} else {
delimiter.addLast(Delimiter.findDelimiter(s));
}
});
return numbers.stream()
.reduce((number1, number2) -> number1.calculate(delimiter.pollFirst(), number2))
.orElseThrow(RuntimeException::new);
}
public void printResult() {
System.out.println("result is " + this.result.getNumber());
}
}