forked from woowacourse-precourse/java-calculator-8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplication.java
More file actions
74 lines (59 loc) · 1.96 KB
/
Application.java
File metadata and controls
74 lines (59 loc) · 1.96 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package calculator;
import camp.nextstep.edu.missionutils.Console;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Application {
public static void main(String[] args) {
System.out.println("덧셈할 문자열을 입력해 주세요.");
String input = Console.readLine();
try {
int result = add(input);
System.out.println("결과 : " + result);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e);
}
}
public static String[] splitNumber(String text) {
String delimiter = ",|:";
String numbersText = text;
if (text.startsWith("//")) {
Matcher matcher = Pattern.compile("//(.)\\\\n(.*)").matcher(text);
if (matcher.matches()) {
delimiter = Pattern.quote(matcher.group(1));
numbersText = matcher.group(2);
}
}
return numbersText.split(delimiter);
}
public static int add(String input) {
if (input == null || input.isEmpty()) {
return 0;
}
String[] numbers = splitNumber(input);
return sum(numbers);
}
public static int sum(String[] numbers) {
int sum = 0;
List<Integer> negativeNumbers = new ArrayList<>();
for (String numberStr : numbers) {
if (numberStr.trim().isEmpty()) {
continue;
}
try {
int number = Integer.parseInt(numberStr.trim());
if (number < 0) {
throw new IllegalArgumentException("잘못");
}
sum += number;
} catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
}
if (!negativeNumbers.isEmpty()) {
throw new IllegalArgumentException();
}
return sum;
}
}