forked from next-step/java-calculator-unit-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCalculator.java
More file actions
40 lines (32 loc) · 943 Bytes
/
StringCalculator.java
File metadata and controls
40 lines (32 loc) · 943 Bytes
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
public class StringCalculator {
public int add(String string) {
if (string.isEmpty()) {
return 0;
}
String[] numbers = string.split(",|:");
return sum(numbers);
}
private int sum(String[] numbers) {
int total = 0;
for (String number : numbers) {
int num = checkNumber(number);
total += num;
}
return total;
}
private int checkNumber(String number) {
if (number.isEmpty()) {
return 0;
}
// 숫자가 아닌 경우 RuntimeException 발생
try {
int num = Integer.parseInt(number);
if (num < 0) {
throw new RuntimeException("음수가 포함되어 있습니다.");
}
return num;
} catch (NumberFormatException e) {
throw new RuntimeException("잘못된 입력입니다.");
}
}
}