-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMain.java
More file actions
77 lines (62 loc) · 1.79 KB
/
Main.java
File metadata and controls
77 lines (62 loc) · 1.79 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Calculator cal = new Calculator();
}
public static class Calculator {
int add(int i, int j){
return i + j;
}
int subtract(int i, int j) {
return i - j;
}
int multiply(int i, int j) {
return i * j;
}
int divide(int i, int j) {
return i / j;
}
}
public static class StringCalculator {
public int add(String text) {
if (toBlank(text)) {
return 0;
}
return sum(toInts(split(text)));
}
private boolean toBlank(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 < values.length; i++) {
numbers[i] = toPositive(values[i]);
}
return numbers;
}
private int sum(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
private int toPositive(String value) {
int number = Integer.parseInt(value);
if (number < 0) {
throw new RuntimeException();
}
return number;
}
}
}