Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
# java-calculator-precourse
## 구현할 기능 목록
- [ ] 빈 문자열 또는 null 입력이면 0 반환
- [ ] 쉼표(,), 콜론(:)을 구분자로 가지는 문자열은 분리하여 합산
- [ ] 커스텀 구분자 지정 가능("//<구분자>\n" 형식, 한 글자)
- [ ] 잘못된 입력(숫자 이외, 음수·0, 공백 등 비정상 형식) 시 IllegalArgumentException 발생
- [ ] 입출력: Console.readLine()으로 입력 받고 "결과 : <합>" 출력
- [ ] IllegalArgumentException 발생 후 애플리케이션 종료
9 changes: 8 additions & 1 deletion src/main/java/calculator/Application.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
package calculator;

import camp.nextstep.edu.missionutils.Console;

public class Application {
public static void main(String[] args) {
// TODO: 프로그램 구현

System.out.println("덧셈할 문자열을 입력해 주세요.");
String input = Console.readLine();

int result = StringAddCalculator.add(input);
System.out.println("결과 : " + result);
}
}
48 changes: 48 additions & 0 deletions src/main/java/calculator/StringAddCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package calculator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringAddCalculator {
private static final String DEFAULT_DELIMS = "[,:]";
private static final Pattern CUSTOM = Pattern.compile("^//(.)\\n(.*)$"); // //;\n1;2;3

private StringAddCalculator() {}

public static int add(String input) {
if (input == null || input.isBlank()) return 0;

input = input.replace("\\n", "\n");

String[] tokens = tokenize(input);
validate(tokens);

long sum = 0;
for (String t : tokens) {
int n = Integer.parseInt(t);
sum += n;
if (sum > Integer.MAX_VALUE) throw new IllegalArgumentException("[ERROR] int overflow");
}
return (int) sum;
}

private static String[] tokenize(String input) {
Matcher m = CUSTOM.matcher(input);
if (m.matches()) {
String delim = Pattern.quote(m.group(1)); // 1글자 커스텀 구분자
String body = m.group(2);
if (body.isEmpty()) throw new IllegalArgumentException("[ERROR] 잘못된 입력 형식");
return body.split(delim);
}
return input.split(DEFAULT_DELIMS);
}

private static void validate(String[] tokens) {
for (String s : tokens) {
if (s == null || s.isBlank()) throw new IllegalArgumentException("[ERROR] 빈 토큰");
if (!s.matches("\\d+")) throw new IllegalArgumentException("[ERROR] 숫자만 허용");
int n = Integer.parseInt(s);
if (n <= 0) throw new IllegalArgumentException("[ERROR] 0/음수 불가");
}
}
}