diff --git a/README.md b/README.md index bd90ef0247..6f5139db06 100644 --- a/README.md +++ b/README.md @@ -1 +1,4 @@ -# java-calculator-precourse \ No newline at end of file +# java-calculator-precourse + +1. 커스텀 문자열을 두 개이상의 문자를 받아 커스텀으로 만들기 +2. 덧셈구현 외에도 계산기 시스템 모방하기 \ No newline at end of file diff --git a/src/main/java/calculator/Application.java b/src/main/java/calculator/Application.java index 573580fb40..f600cbd54b 100644 --- a/src/main/java/calculator/Application.java +++ b/src/main/java/calculator/Application.java @@ -1,7 +1,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) { - // TODO: 프로그램 구현 + 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 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; } -} +} \ No newline at end of file