11public class Calculator {
2- int add (int a , int b ){
2+ int add (int a , int b ) {
33 return a + b ;
44 }
5+
56 int subtract (int a , int b ){
67 return a - b ;
78 }
@@ -11,4 +12,39 @@ int multiply(int a, int b){
1112 int divide (int a , int b ){
1213 return a / b ;
1314 }
15+
16+ public int calculateString (String input ) {
17+ if (input == null | input .isEmpty ()) {
18+ return 0 ;
19+ }
20+
21+ String separator = "[,:]" ;//정규표현식. split()메소드에서 사용된다. '[]안의 문자중 하나와 일치'라는 의미를 갖는다.
22+ String numbersStr = input ;
23+
24+ if (input .substring (0 , 2 ).equals ("//" )) {
25+ int slashStartIndex = input .indexOf ("//" );
26+ int newLineStartIndex = input .indexOf ("/n" );
27+
28+ if (newLineStartIndex != -1 ) {
29+ String customSeparator = input .substring (slashStartIndex + 2 , newLineStartIndex );
30+ separator = "[,:" + customSeparator + "]" ;
31+ numbersStr = input .substring (newLineStartIndex + 1 );//개행문자는 하나의 문자로 취급.
32+ }
33+ }
34+
35+ String [] numbers = numbersStr .split (separator );
36+
37+ int sum = 0 ;
38+ for (String number : numbers ) {
39+ if (!number .isEmpty ()) {
40+ int value = Integer .parseInt (number );//String 배열에 있는 numbers를 하나씩 int형으로 변환
41+ if (value < 0 ) {
42+ throw new RuntimeException ("음수는 사용할 수 없습니다 : " + value );
43+ }
44+ sum += value ;
45+ }
46+ }
47+ return sum ;
48+ }
1449}
50+
0 commit comments