forked from next-step/java-racingcar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringAddCalculator.java
57 lines (44 loc) · 1.68 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
package calculator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringAddCalculator {
private static final Pattern DEFAULT_DELIMITERS_PATTERN = Pattern.compile("[,:]");
private static final Pattern CUSTOM_DELIMITER_PARSE_PATTERN = Pattern.compile("//(.)\n(.*)");
public static final String VALID_INTEGER_PATTERN = "-?\\d+";
public static int splitAndSum(String text) {
if (text == null || text.isEmpty()) {
return 0;
}
List<String> tokens = splitIntoTokens(text);
return sumPositiveNumbersOrThrow(tokens);
}
private static List<String> splitIntoTokens(String text) {
Matcher matcher = CUSTOM_DELIMITER_PARSE_PATTERN.matcher(text);
if (matcher.find()) {
String customDelimiter = Pattern.quote(matcher.group(1));
return List.of(matcher.group(2).split(customDelimiter));
}
return List.of(DEFAULT_DELIMITERS_PATTERN.split(text));
}
private static int sumPositiveNumbersOrThrow(List<String> tokens) {
int sum = 0;
for (String token : tokens) {
if (!isValidInteger(token)) {
throw new RuntimeException("Invalid input: " + token);
}
int num = Integer.parseInt(token);
if (num < 0) {
throw new RuntimeException("Negative numbers not allowed: " + token);
}
sum += num;
}
return sum;
}
private static boolean isValidInteger(String input) {
if (input == null || input.isEmpty()) {
return false;
}
return input.matches(VALID_INTEGER_PATTERN);
}
}