diff --git a/README.md b/README.md index 5fa2560..c9bc93f 100644 --- a/README.md +++ b/README.md @@ -1 +1,140 @@ -# java-lotto-precourse +# 3주차 미션 : 로또 +
+ 과제 세부 내용 + +## 과제 +- 로또 게임 기능을 구현해야 한다. 로또 게임은 아래와 같은 규칙으로 진행된다. + + - 로또 번호의 숫자 범위는 1~45까지이다. + - 1개의 로또를 발행할 때 중복되지 않는 6개의 숫자를 뽑는다. + - 당첨 번호 추첨 시 중복되지 않는 숫자 6개와 보너스 번호 1개를 뽑는다. + - 당첨은 1등부터 5등까지 있다. 당첨 기준과 금액은 아래와 같다. + - 1등 : 6개 번호 일치 / 2,000,000,000원 + - 2등 : 5개 번호 + 보너스 번호 일치 / 30,000,000원 + - 3등 : 5개 번호 일치 / 1,500,000원 + - 4등 : 4개 번호 일치 / 50,000원 + - 5등 : 3개 번호 일치 / 5,000원 + - 로또 구입 금액을 입력하면 구입 금액에 해당하는 만큼 로또를 발행해야 한다. + - 로또 1장의 가격은 1,000원이다. + - 당첨 번호와 보너스 번호를 입력받는다. + - 사용자가 구매한 로또 번호와 당첨 번호를 비교하여 당첨 내역 및 수익률을 출력하고 로또 게임을 종료한다. + - 사용자가 잘못된 값을 입력할 경우 `IllegalArgumentException`를 발생시키고, "[ERROR]"로 시작하는 에러 메시지를 출력 후 그 부분부터 입력을 다시 받는다. + - `Exception`이 아닌 `IllegalArgumentException`, `IllegalStateException` 등과 같은 명확한 유형을 처리한다. +### 입출력 +- 로또 구입 금액을 입력 받는다. 구입 금액은 1,000원 단위로 입력 받으며 1,000원으로 나누어 떨어지지 않는 경우 예외 처리한다. + + 14000 + +- 당첨 번호를 입력 받는다. 번호는 쉼표(,)를 기준으로 구분한다. + + 1,2,3,4,5,6 + +- 보너스 번호를 입력 받는다. + + 7 + +- 발행한 로또 수량 및 번호를 출력한다. 로또 번호는 오름차순으로 정렬하여 보여준다. + + 8개를 구매했습니다. + [8, 21, 23, 41, 42, 43] + [3, 5, 11, 16, 32, 38] + [7, 11, 16, 35, 36, 44] + [1, 8, 11, 31, 41, 42] + [13, 14, 16, 38, 42, 45] + [7, 11, 30, 40, 42, 43] + [2, 13, 22, 32, 38, 45] + [1, 3, 5, 14, 22, 45] + +- 당첨 내역을 출력한다. + + 3개 일치 (5,000원) - 1개 + 4개 일치 (50,000원) - 0개 + 5개 일치 (1,500,000원) - 0개 + 5개 일치, 보너스 볼 일치 (30,000,000원) - 0개 + 6개 일치 (2,000,000,000원) - 0개 + +- 수익률은 소수점 둘째 자리에서 반올림한다. (ex. 100.0%, 51.5%, 1,000,000.0%) + + 총 수익률은 62.5%입니다. + +- 예외 상황 시 에러 문구를 출력해야 한다. 단, 에러 문구는 "[ERROR]"로 시작해야 한다. + + [ERROR] 로또 번호는 1부터 45 사이의 숫자여야 합니다. + +### 실행 결과 예시 + 구입금액을 입력해 주세요. + 8000 + + 8개를 구매했습니다. + [8, 21, 23, 41, 42, 43] + [3, 5, 11, 16, 32, 38] + [7, 11, 16, 35, 36, 44] + [1, 8, 11, 31, 41, 42] + [13, 14, 16, 38, 42, 45] + [7, 11, 30, 40, 42, 43] + [2, 13, 22, 32, 38, 45] + [1, 3, 5, 14, 22, 45] + + 당첨 번호를 입력해 주세요. + 1,2,3,4,5,6 + + 보너스 번호를 입력해 주세요. + 7 + + 당첨 통계 + --- + 3개 일치 (5,000원) - 1개 + 4개 일치 (50,000원) - 0개 + 5개 일치 (1,500,000원) - 0개 + 5개 일치, 보너스 볼 일치 (30,000,000원) - 0개 + 6개 일치 (2,000,000,000원) - 0개 + 총 수익률은 62.5%입니다. + +### 요구 사항 +- indent(인덴트, 들여쓰기) depth를 3이 넘지 않도록 구현한다. 2까지만 허용한다. + - 예를 들어 while문 안에 if문이 있으면 들여쓰기는 2이다. + - 힌트: indent(인덴트, 들여쓰기) depth를 줄이는 좋은 방법은 함수(또는 메서드)를 분리하면 된다. +- 3항 연산자를 쓰지 않는다. +- 함수(또는 메서드)가 한 가지 일만 하도록 최대한 작게 만들어라. +- JUnit 5와 AssertJ를 이용하여 본인이 정리한 기능 목록이 정상 동작함을 테스트 코드로 확인한다. +- 함수(또는 메서드)의 길이가 15라인을 넘어가지 않도록 구현한다. + - 함수(또는 메서드)가 한 가지 일만 잘 하도록 구현한다. +- else 예약어를 쓰지 않는다. + - 힌트: if 조건절에서 값을 return하는 방식으로 구현하면 else를 사용하지 않아도 된다. + - else를 쓰지 말라고 하니 switch/case로 구현하는 경우가 있는데 switch/case도 허용하지 않는다. +- Java Enum을 적용한다. +- 도메인 로직에 단위 테스트를 구현해야 한다. 단, UI(System.out, [System.in](http://system.in/), Scanner) 로직은 제외한다. + - 핵심 로직을 구현하는 코드와 UI를 담당하는 로직을 분리해 구현한다. + - 단위 테스트 작성이 익숙하지 않다면 `test/java/lotto/LottoTest`를 참고하여 학습한 후 테스트를 구현한다. + +
+ +## 구현할 기능 목록 +### Model + Lotto + - numbers[List] + LottoData + - 로또[List] + - 당첨 번호[List] + - 보너스 번호[int] + - 등수 결과[intArray[5]] +### Utils + - Enum + - 로또 번호 생성 + - 입력값 검증 +### Service + Calculator + - 로또 장수 계산 + - 수익률 계산 + LottoService + - 당첨 로또 확인 +### View + - 구입 금액 입력 + - 당첨 번호 입력 + - 보너스 번호 입력 + - 발행한 로또 수량 및 번호 출력 + - 당첨 내역 및 수익률 출력 +### Controller + - 입력값으로 객체들 선언 및 초기화 + - 로또 확인 + - 결과 출력 \ No newline at end of file diff --git a/src/main/java/lotto/AppConfig.java b/src/main/java/lotto/AppConfig.java new file mode 100644 index 0000000..0a94bfb --- /dev/null +++ b/src/main/java/lotto/AppConfig.java @@ -0,0 +1,34 @@ +package lotto; + +import lotto.controller.LottoController; +import lotto.service.Calculator; +import lotto.service.LottoService; +import lotto.view.InputView; +import lotto.view.OutputView; + +public class AppConfig { + public InputView inputView() { + return new InputView(); + } + + public OutputView outputView() { + return new OutputView(); + } + + public Calculator calculator() { + return new Calculator(); + } + + public LottoService lottoService() { + return new LottoService(); + } + + public LottoController lottoController() { + return new LottoController( + inputView(), + outputView(), + calculator(), + lottoService() + ); + } +} diff --git a/src/main/java/lotto/Application.java b/src/main/java/lotto/Application.java index d190922..1a83972 100644 --- a/src/main/java/lotto/Application.java +++ b/src/main/java/lotto/Application.java @@ -1,7 +1,11 @@ package lotto; +import lotto.controller.LottoController; + public class Application { public static void main(String[] args) { - // TODO: 프로그램 구현 + AppConfig appConfig = new AppConfig(); + LottoController controller = appConfig.lottoController(); + controller.run(); } } diff --git a/src/main/java/lotto/controller/LottoController.java b/src/main/java/lotto/controller/LottoController.java new file mode 100644 index 0000000..d94e7f2 --- /dev/null +++ b/src/main/java/lotto/controller/LottoController.java @@ -0,0 +1,68 @@ +package lotto.controller; + +import lotto.service.Calculator; +import lotto.service.LottoService; +import lotto.utils.ErrorConstants; +import lotto.utils.RandomNumber; +import lotto.utils.Validator; +import lotto.view.InputView; +import lotto.view.OutputView; + +import java.util.List; + +public class LottoController { + InputView inputView; + OutputView outputView; + Calculator calculator; + LottoService lottoService; + + private int money; + private double profit; + + public LottoController(InputView inputView, OutputView outputView, Calculator calculator, LottoService lottoService) { + this.inputView = inputView; + this.outputView = outputView; + this.calculator = calculator; + this.lottoService = lottoService; + } + + public void run() { + initialize(); + execute(); + printResult(); + } + + private void initialize() { + this.money = inputView.insertMoney(); + outputView.newLine(); + List> lottos = RandomNumber.pickNumbers(calculator.calculateSheet(money)); + outputView.printLotto(lottos); + outputView.newLine(); + List numbers = inputView.selectNumber(); + outputView.newLine(); + int bonusNumber = readBonusNumber(numbers); + outputView.newLine(); + lottoService.init(lottos, numbers, bonusNumber); + } + + private void execute() { + lottoService.matchNumber(); + profit = calculator.calculateProfit(money, lottoService.getResult()); + } + + private void printResult() { + outputView.printStats(lottoService.getResult(), profit); + } + + private int readBonusNumber(List numbers) { + int bn; + while (true) { + try { + bn = Validator.checkDistinctBonusNumber(inputView.selectBonusNumber(), numbers); + return bn; + } catch (IllegalArgumentException e) { + System.out.println(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + } +} diff --git a/src/main/java/lotto/Lotto.java b/src/main/java/lotto/model/Lotto.java similarity index 64% rename from src/main/java/lotto/Lotto.java rename to src/main/java/lotto/model/Lotto.java index 88fc5cf..72dde63 100644 --- a/src/main/java/lotto/Lotto.java +++ b/src/main/java/lotto/model/Lotto.java @@ -1,4 +1,4 @@ -package lotto; +package lotto.model; import java.util.List; @@ -7,14 +7,17 @@ public class Lotto { public Lotto(List numbers) { validate(numbers); - this.numbers = numbers; + this.numbers = numbers.stream().sorted().toList(); } private void validate(List numbers) { + numbers = numbers.stream().distinct().toList(); if (numbers.size() != 6) { throw new IllegalArgumentException("[ERROR] 로또 번호는 6개여야 합니다."); } } - // TODO: 추가 기능 구현 + public List getNumbers() { + return numbers; + } } diff --git a/src/main/java/lotto/model/LottoData.java b/src/main/java/lotto/model/LottoData.java new file mode 100644 index 0000000..db5d4b3 --- /dev/null +++ b/src/main/java/lotto/model/LottoData.java @@ -0,0 +1,47 @@ +package lotto.model; + +import java.util.ArrayList; +import java.util.List; + +public class LottoData { + private final List lottos; + private final List numbers; + private int bonusNumber; + private final int[] result; + + private LottoData() { + lottos = new ArrayList<>(); + numbers = new ArrayList<>(); + bonusNumber = 0; + result = new int[5]; + } + + public static LottoData init(List> l, List n, int bn) { + LottoData data = new LottoData(); + data.lottos.addAll(l.stream().map(Lotto::new).toList()); + data.numbers.addAll(n); + data.bonusNumber = bn; + data.numbers.add(data.bonusNumber); + return data; + } + + public List getLottos() { + return lottos; + } + + public List getNumbers() { + return numbers; + } + + public int getBonusNumber() { + return bonusNumber; + } + + public int[] getResult() { + return result; + } + + public void addPrize(int number) { + result[number]++; + } +} diff --git a/src/main/java/lotto/service/Calculator.java b/src/main/java/lotto/service/Calculator.java new file mode 100644 index 0000000..95f440d --- /dev/null +++ b/src/main/java/lotto/service/Calculator.java @@ -0,0 +1,17 @@ +package lotto.service; + +import lotto.utils.PrizeConstants; + +public class Calculator { + public int calculateSheet(int money) { + return money/1000; + } + + public double calculateProfit(int money, int[] result) { + PrizeConstants[] p = PrizeConstants.values(); + double sum = 0; + for (int i = 0; i < result.length; i++) + sum += result[i] * p[i].getPrize(); + return Math.round(sum/(double)money*100 * 100) / 100.0; + } +} diff --git a/src/main/java/lotto/service/LottoService.java b/src/main/java/lotto/service/LottoService.java new file mode 100644 index 0000000..cbcd6ff --- /dev/null +++ b/src/main/java/lotto/service/LottoService.java @@ -0,0 +1,35 @@ +package lotto.service; + +import lotto.model.Lotto; +import lotto.model.LottoData; + +import java.util.List; + +public class LottoService { + private LottoData lottoData; + + public void init(List> l, List n, int bn) { + this.lottoData = LottoData.init(l, n, bn); + } + + public int[] getResult() { + return lottoData.getResult(); + } + + public void matchNumber() { + List intersectionList; + for (Lotto l : lottoData.getLottos()) { + intersectionList = l.getNumbers().stream().filter(n -> lottoData.getNumbers().contains(n)).toList(); + if (intersectionList.size() < 3) continue; + if (intersectionList.size() == 6 && !isContainBonus(intersectionList)) { + lottoData.addPrize(4); + continue; + } + lottoData.addPrize(intersectionList.size() - 3); + } + } + + private boolean isContainBonus(List l) { + return l.contains(lottoData.getBonusNumber()); + } +} diff --git a/src/main/java/lotto/utils/ErrorConstants.java b/src/main/java/lotto/utils/ErrorConstants.java new file mode 100644 index 0000000..b5224d6 --- /dev/null +++ b/src/main/java/lotto/utils/ErrorConstants.java @@ -0,0 +1,15 @@ +package lotto.utils; + +public enum ErrorConstants { + INPUT_ERROR("[ERROR] 입출력 과정에서 예외가 발생했습니다."); + + private final String message; + + ErrorConstants(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/lotto/utils/MessageConstants.java b/src/main/java/lotto/utils/MessageConstants.java new file mode 100644 index 0000000..725b5f4 --- /dev/null +++ b/src/main/java/lotto/utils/MessageConstants.java @@ -0,0 +1,19 @@ +package lotto.utils; + +public enum MessageConstants { + FIFTH_PRIZE("3개 일치 (5,000원)"), + FOURTH_PRIZE("4개 일치 (50,000원)"), + THIRD_PRIZE("5개 일치 (1,500,000원)"), + SECOND_PRIZE("5개 일치, 보너스 볼 일치 (30,000,000원)"), + FIRST_PRIZE("6개 일치 (2,000,000,000원)"); + + private final String message; + + MessageConstants(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/lotto/utils/PrizeConstants.java b/src/main/java/lotto/utils/PrizeConstants.java new file mode 100644 index 0000000..2030c8b --- /dev/null +++ b/src/main/java/lotto/utils/PrizeConstants.java @@ -0,0 +1,19 @@ +package lotto.utils; + +public enum PrizeConstants { + FIFTH_PRIZE("5000"), + FOURTH_PRIZE("50000"), + THIRD_PRIZE("1500000"), + SECOND_PRIZE("30000000"), + FIRST_PRIZE("2000000000"); + + private final int value; + + PrizeConstants(String value) { + this.value = Integer.parseInt(value); + } + + public int getPrize() { + return value; + } +} diff --git a/src/main/java/lotto/utils/RandomNumber.java b/src/main/java/lotto/utils/RandomNumber.java new file mode 100644 index 0000000..a9d094f --- /dev/null +++ b/src/main/java/lotto/utils/RandomNumber.java @@ -0,0 +1,19 @@ +package lotto.utils; + +import camp.nextstep.edu.missionutils.Randoms; + +import java.util.ArrayList; +import java.util.List; + +public class RandomNumber { + public static List> pickNumbers(int n) { + List> list = new ArrayList<>(); + for (int i = 0; i < n; i++) { + list.add(Randoms.pickUniqueNumbersInRange(1, 45, 6) + .stream() + .sorted() + .toList()); + } + return list; + } +} diff --git a/src/main/java/lotto/utils/Validator.java b/src/main/java/lotto/utils/Validator.java new file mode 100644 index 0000000..862fc79 --- /dev/null +++ b/src/main/java/lotto/utils/Validator.java @@ -0,0 +1,58 @@ +package lotto.utils; + +import java.util.Arrays; +import java.util.List; + +public class Validator { + public static int checkMoney(String input) { + try { + double money = Integer.parseInt(input); + if (!isInteger(money/1000)) { throw new IllegalArgumentException(); } + return (int) money; + } catch (Exception e) { + throw new IllegalArgumentException(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + + public static List checkPrizeNumbers(String input) { + try { + List n = Arrays.stream(input.trim().split(",")) + .mapToInt(Integer::parseInt) + .filter(Validator::isUnder45) + .distinct() + .boxed() + .toList(); + if (n.size() < 6) { throw new IllegalArgumentException(); } + return n; + } catch (Exception e) { + throw new IllegalArgumentException(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + + public static int checkBonusNumber(String input) { + try { + int bn = Integer.parseInt(input); + if (!isUnder45(bn)) { throw new IllegalArgumentException(); } + return bn; + } catch (Exception e) { + throw new IllegalArgumentException(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + + public static int checkDistinctBonusNumber(int input, List numbers) { + try { + if (numbers.contains(input)) { throw new IllegalArgumentException(); } + return input; + } catch (Exception e) { + throw new IllegalArgumentException(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + + private static boolean isUnder45(int number) { + return number < 46 && number > 0; + } + + private static boolean isInteger(double number) { + return number % 1 == 0.0; + } +} diff --git a/src/main/java/lotto/view/InputView.java b/src/main/java/lotto/view/InputView.java new file mode 100644 index 0000000..d756cb4 --- /dev/null +++ b/src/main/java/lotto/view/InputView.java @@ -0,0 +1,42 @@ +package lotto.view; + +import camp.nextstep.edu.missionutils.Console; +import lotto.utils.ErrorConstants; +import lotto.utils.Validator; + +import java.util.List; + +public class InputView { + public int insertMoney() { + while (true) { + try { + System.out.println("구입금액을 입력해 주세요."); + return Validator.checkMoney(Console.readLine()); + } catch (IllegalArgumentException e) { + System.out.println(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + } + + public List selectNumber() { + while (true) { + try { + System.out.println("당첨 번호를 입력해 주세요."); + return Validator.checkPrizeNumbers(Console.readLine()); + } catch (IllegalArgumentException e) { + System.out.println(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + } + + public int selectBonusNumber() { + while (true) { + try { + System.out.println("보너스 번호를 입력해 주세요."); + return Validator.checkBonusNumber(Console.readLine()); + } catch (IllegalArgumentException e) { + System.out.println(ErrorConstants.INPUT_ERROR.getMessage()); + } + } + } +} diff --git a/src/main/java/lotto/view/OutputView.java b/src/main/java/lotto/view/OutputView.java new file mode 100644 index 0000000..9213a78 --- /dev/null +++ b/src/main/java/lotto/view/OutputView.java @@ -0,0 +1,25 @@ +package lotto.view; + +import lotto.utils.MessageConstants; + +import java.util.List; + +public class OutputView { + public void printLotto(List> l) { + System.out.println(l.size() + "개를 구매했습니다."); + l.forEach(System.out::println); + } + + public void printStats(int[] results, double profit) { + System.out.println("당첨 통계\n---"); + MessageConstants[] m = MessageConstants.values(); + for (int i = 0; i < results.length; i++) { + System.out.println(m[i].getMessage() + " - " + results[i] + "개"); + } + System.out.println("총 수익률은 " + String.format("%.1f", profit) + "%입니다."); + } + + public void newLine() { + System.out.println(); + } +} diff --git a/src/test/java/lotto/LottoTest.java b/src/test/java/lotto/LottoTest.java index 309f4e5..c8ca9d6 100644 --- a/src/test/java/lotto/LottoTest.java +++ b/src/test/java/lotto/LottoTest.java @@ -1,5 +1,6 @@ package lotto; +import lotto.model.Lotto; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test;