forked from next-step/java-racingcar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringAddCalculator.java
74 lines (60 loc) · 2.13 KB
/
StringAddCalculator.java
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
package step2;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
public class StringAddCalculator {
public static final List<String> DEFAULT_DELIMITER = List.of(",", ":");
private static final int GROUP_INDEX_DELIMITER = 1;
private static final int GROUP_INDEX_NUMBERS = 2;
/**
* 문자열 덧셈 계산기
*
* @param input 입력값
* @return 계산 결과
*/
public static int calculate(String input) {
if (isNullOrBlack(input)) {
return 0;
}
return sum(toInts(split(input)));
}
private static boolean isNullOrBlack(String input) {
return input == null || input.isBlank();
}
private static List<String> split(String input) {
Matcher customMatcher = CalculatorMatcher.getCustomMatcher(input);
if (customMatcher.find()) {
return splitWithCustomDelimiter(customMatcher);
}
return List.of(input.split(defaultDelimiterRegex()));
}
private static List<String> splitWithCustomDelimiter(Matcher customMatcher) {
return Arrays.stream(customMatcher.group(GROUP_INDEX_NUMBERS)
.split(customMatcher.group(GROUP_INDEX_DELIMITER)))
.collect(Collectors.toList());
}
public static String defaultDelimiterRegex() {
return "[" + String.join("", DEFAULT_DELIMITER) + "]";
}
private static List<Integer> toInts(List<String> values) {
return values.stream()
.map(value -> toInt(value))
.collect(Collectors.toList());
}
private static int toInt(String value) {
int number = Integer.parseInt(value);
checkNegativeNumber(number);
return number;
}
private static void checkNegativeNumber(int number) {
if (number < 0) {
throw new RuntimeException(String.format("음수(%s)는 사용할 수 없습니다.", number));
}
}
private static int sum(List<Integer> values) {
return values.stream()
.mapToInt(Integer::intValue)
.sum();
}
}