-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStringCalculator.java
More file actions
49 lines (41 loc) · 1.17 KB
/
StringCalculator.java
File metadata and controls
49 lines (41 loc) · 1.17 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
package calculator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringCalculator {
public int add(String text) {
if(isBlank(text)) return 0;
return sum(toInts(split(text)));
}
private boolean isBlank(String text) {
return text == null || text.isEmpty();
}
private String[] split(String text) {
Matcher m = Pattern.compile("//(.)\n(.*)").matcher(text);
if(m.find()) {
String customDelimeter = m.group(1);
return m.group(2).split(customDelimeter);
}
return text.split(",|:");
}
private int[] toInts(String[] values) {
int[] numbers = new int[values.length];
for (int i=0; i<numbers.length; i++) {
numbers[i] = toPositive(values[i]);
}
return numbers;
}
private int toPositive(String value) {
int number = Integer.parseInt(value);
if(number < 0) {
throw new RuntimeException();
}
return number;
}
private int sum(int[] numbers) {
int sum = 0;
for(int number : numbers) {
sum += number;
}
return sum;
}
}