-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathStringCalculator.java
More file actions
58 lines (50 loc) · 1.37 KB
/
Copy pathStringCalculator.java
File metadata and controls
58 lines (50 loc) · 1.37 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
//possibly misunderstood the task, unsure if it was supposed to add only one digit numbers, like I did or are numbers like 231 ok
//not finished anyway
import java.util.ArrayList;
import java.util.List;
public class StringCalculator {
private List<Integer> numbers = new ArrayList<>();
public int add(String numbersStr) throws StringCalculatorException{
if(checkIfStringContainsOnlyNumbersAndAcceptableCharacters(numbersStr) && checkIfCharacterIsANumber(numbersStr.charAt(0))) {
int counter = 0;
for(char c: numbersStr.toCharArray()) {
if(counter%2 == 0) {
if (checkIfCharacterIsANumber(c)) {
numbers.add(Character.getNumericValue(c));
}
else {
throw new StringCalculatorException("String contains too many 'break' characters in a row");
}
}
counter++;
}
int result = 0;
for(int r: numbers) {
result += r;
}
return result;
}
else {
throw new StringCalculatorException("String contains more than just numbers");
}
//
}
private boolean checkIfStringContainsOnlyNumbersAndAcceptableCharacters(String s) {
for(char c: s.toCharArray()) {
if(!Character.isDigit(c)) {
if(c == ',' || c == '\r' || c == '\n') {
}
else {
return false;
}
}
}
return true;
}
private boolean checkIfCharacterIsANumber(char c) {
if(Character.isDigit(c)) {
return true;
}
return false;
}
}