-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathStringCalculator.java
More file actions
59 lines (45 loc) · 1.2 KB
/
StringCalculator.java
File metadata and controls
59 lines (45 loc) · 1.2 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
public class StringCalculator {
static final int[] validNumbers = {0, 1, 2};
// Returns the sum of the numbers given in numbersStr
public int add(String numbersStr) throws StringCalculatorException {
int [] numbers;
int result;
if (numbersStr.length() == 0) {
return 0;
}
numbers = StringArrayToInt(numbersStr.split(",|\\n"));
result = calculateNumbers(numbers);
return result;
}
private int[] StringArrayToInt(String[] strNumbers) throws StringCalculatorException {
int[] intNumbers = new int[strNumbers.length];
int tempInt;
for (int i = 0; i < strNumbers.length; i++) {
// Try converting part of the string to a integer
try {
tempInt = Integer.parseInt(strNumbers[i]);
}
catch(Exception e) {
throw (new StringCalculatorException());
}
validateNumber(tempInt);
intNumbers[i] = tempInt;
}
return intNumbers;
}
private void validateNumber(int number) throws StringCalculatorException {
for (int i: validNumbers) {
if (i == number) {
return;
}
}
throw (new StringCalculatorException());
}
private int calculateNumbers(int[] numbers) {
int sum = 0;
for (int x: numbers) {
sum += x;
}
return sum;
}
}