@@ -13,22 +13,13 @@ public class StringCalculator {
13
13
private final String delimeterRegex = "[,|:]" ;
14
14
15
15
public int calculate (String str ) {
16
- String [] tokens ;
17
- String customDelimeter ;
18
-
19
16
if (str == null || str .isBlank ()) {
20
17
throw new RuntimeException (EMPTY_STRING );
21
18
}
22
19
23
- customDelimeter = findCustomDelimeter (str );
24
-
25
- if (customDelimeter == null ) {
26
- tokens = str .split (delimeterRegex );
27
- } else {
28
- tokens = str .substring (str .indexOf ("\n " ) + 1 )
29
- .split (Pattern .quote (customDelimeter ));
30
- }
31
-
20
+ String customDelimeter = findCustomDelimeter (str );
21
+ String strNumbers = extractNumber (str , customDelimeter );
22
+ String [] tokens = splitTokens (strNumbers , customDelimeter );
32
23
List <Integer > numbers = parseNumber (tokens );
33
24
34
25
return add (numbers );
@@ -49,24 +40,42 @@ public String findCustomDelimeter(String str) {
49
40
return str .substring (startDelimeterIdx + 2 , endDelimeterIdx );
50
41
}
51
42
43
+ public String extractNumber (String str , String customDelimeter ) {
44
+ if (customDelimeter != null ) {
45
+ return str .substring (str .indexOf ("\n " ) + 1 );
46
+ }
47
+
48
+ return str ;
49
+ }
50
+
51
+ public String [] splitTokens (String strNumbers , String customDelimeter ) {
52
+ if (customDelimeter == null ) {
53
+ return strNumbers .split (delimeterRegex );
54
+ }
55
+
56
+ return strNumbers .split (Pattern .quote (customDelimeter ));
57
+ }
58
+
52
59
public List <Integer > parseNumber (String [] tokens ) {
53
60
return Arrays .stream (tokens )
54
- .map (token -> {
55
- try {
56
- int number = Integer .parseInt (token .trim ());
57
-
58
- if (number < 0 ) {
59
- throw new RuntimeException (NEGATIVE_NUMBER_NOT_ALLOWED );
60
- }
61
-
62
- return number ;
63
- } catch (NumberFormatException ex ) {
64
- throw new RuntimeException (INVALID_STRING );
65
- }
66
- })
61
+ .map (this ::parseTokenToInt )
67
62
.toList ();
68
63
}
69
64
65
+ public int parseTokenToInt (String token ) {
66
+ try {
67
+ int number = Integer .parseInt (token .trim ());
68
+
69
+ if (number < 0 ) {
70
+ throw new RuntimeException (NEGATIVE_NUMBER_NOT_ALLOWED );
71
+ }
72
+
73
+ return number ;
74
+ } catch (NumberFormatException ex ) {
75
+ throw new RuntimeException (INVALID_STRING );
76
+ }
77
+ }
78
+
70
79
public int add (List <Integer > numbers ) {
71
80
return numbers .stream ()
72
81
.mapToInt (Integer ::intValue )
0 commit comments