diff --git a/README.md b/README.md index bd90ef0247..b9b93d59c3 100644 --- a/README.md +++ b/README.md @@ -1 +1,15 @@ -# java-calculator-precourse \ No newline at end of file +# java-calculator-precourse + +## 기능 요구사항 + +### 1. 입력한 문자열에서 숫자를 추출하여 더하는 계산기 구현 +- 문자열에 있는 숫자를 구분자 기준으로 구분 후 합산 + +### 2. 구분자 처리 +- 쉼표(,)와 콜론(:)을 기본 구분자로 사용 +- 기본 구분자 외에 //와 \n 사이에 위치하는 문자를 커스텀 구분자로 사용 +- 커스텀 구분자는 1개만 지정 가능 + +### 3. 예외 처리 +- 사용자가 잘못된 값을 입력할 경우 IllegalArgumentException 발생 +- 예외 발생 후 애플리케이션 종료 \ No newline at end of file diff --git a/src/main/java/calculator/Application.java b/src/main/java/calculator/Application.java index 573580fb40..54e415073d 100644 --- a/src/main/java/calculator/Application.java +++ b/src/main/java/calculator/Application.java @@ -1,7 +1,45 @@ package calculator; +import camp.nextstep.edu.missionutils.Console; +import java.util.regex.Pattern; + public class Application { public static void main(String[] args) { - // TODO: 프로그램 구현 + System.out.println("덧셈할 문자열을 입력해 주세요."); + String input = Console.readLine(); + + System.out.println("결과 : " + calculate(input)); + } + + private static int calculate(String input) { + int result=0; + String delimiterPattern = "[,:]"; + + if (input.startsWith("//")) { + int delimiterEndIndex = input.indexOf("\\n"); + if (delimiterEndIndex == -1) { + throw new IllegalArgumentException(); + } + delimiterPattern = Pattern.quote(input.substring(2, delimiterEndIndex)); + input = input.substring(delimiterEndIndex + 2); + } + + if (!input.isEmpty()) { + + String[] numbers = input.split(delimiterPattern); + for (String number : numbers) { + try { + int num = Integer.parseInt(number); + if (num <= 0) { + throw new IllegalArgumentException(); + } + result += num; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(); + } + } + } + + return result; } -} +} \ No newline at end of file