Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[문자열 덧셈 계산기] 김현재 미션 제출합니다 #1911

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
# java-calculator-precourse
# java-calculator-precourse

## 기능 목록

- 입력
- 문자열 파싱
- 숫자 추출 및 변환
- 덧셈 연산 기능
- 예외처리
55 changes: 54 additions & 1 deletion src/main/java/calculator/Application.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,60 @@
package calculator;

import camp.nextstep.edu.missionutils.Console;

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

public class Application {
public static void main(String[] args) {
// TODO: 프로그램 구현
try {
System.out.println("덧셈할 문자열을 입력해 주세요.");
String input = Console.readLine();
int res = calSum(input);
System.out.println("결과 : " + res);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e);
}
}

private static int calSum(String input) {
if (input.isEmpty()) {
return 0;
}
String separator = ",|:";
String numbers = input;

if (input.startsWith("//")) {
/*
"//" : 리터럴
(.) : 구분자로 사용될 문자
"\\\\n" : 실제 \n를 표현 정규표현식
"(.*) : numbers
*/
Matcher matcher = Pattern.compile("//(.)\\\\n(.*)").matcher(input);
if (matcher.find()) {
separator = Pattern.quote(matcher.group(1));
numbers = matcher.group(2);
} else {
throw new IllegalArgumentException("커스텀 구분자 형식이 잘못되었습니다.");
}
}
return Arrays.stream(numbers.split(separator))
.filter(s -> !s.isEmpty())
.mapToInt(Application::parseNumbers)
.sum();
}

private static int parseNumbers(String numbers) {
try {
int number = Integer.parseInt(numbers.trim());
if (number < 0) {
throw new IllegalArgumentException();
}
return number;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("유효하지 않은 숫자 형식: " + numbers);
}
}
}