diff --git a/.gitignore b/.gitignore index 6c018781..1823e4fb 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,7 @@ build/ *.iws *.iml *.ipr -out/ + ### NetBeans ### /nbproject/private/ diff --git a/README.md b/README.md index 814dfeb8..b8d02c8f 100644 --- a/README.md +++ b/README.md @@ -1,231 +1,85 @@ -# 객체지향 코드 연습 - 로또([우아한테크코스 프리코스 - lotto](https://github.com/woowacourse-precourse/java-lotto)) - -## 🔍 진행 방식 - -- 미션은 **기능 요구 사항, 프로그래밍 요구 사항, 과제 진행 요구 사항** 세 가지로 구성되어 있다. -- 세 개의 요구 사항을 만족하기 위해 노력한다. 특히 기능을 구현하기 전에 기능 목록을 만들고, 기능 단위로 커밋 하는 방식으로 진행한다. -- 기능 요구 사항에 기재되지 않은 내용은 스스로 판단하여 구현한다. - -## 📮 미션 제출 방법 - -- 미션 구현을 완료한 후 GitHub을 통해 제출해야 한다. - - 해당 리포지토리를 fork/clone - - 미션 구현 - - 미션 구현 과정에서 학습한 내용, 고민했던 점 등을 기록한 본인 깃헙 아이디 이름 md파일 작성(ex. 5uhwann.md) - - 구현 완료 한 코드는 해당 리포지토리에 pr 작성 - - pr 타이틀: [#주차]객체지향 코드 연습(깃헙 아이디) - - ex. [2주차] 객체지향 코드 연습(TaetaetaE01) - - 미션 구현에서 기록한 md파일은 [COW-Spring-4](https://github.com/COW-edu/COW-Spring-4) 리포지토리에 pr 작성 - 미션 구현 pr 링크 첨부 - -- **해당 리포지토리에만 Pull Request만 보내고 [COW-Spring-4](https://github.com/COW-edu/COW-Spring-4) 리포지토리에 과제를 제출하지 않으면 최종 제출하지 않은 것으로 처리되니 주의한다.** - -## 🚨 과제 제출 전 체크 리스트 - 0점 방지 - -- 기능 구현을 모두 정상적으로 했더라도 **요구 사항에 명시된 출력값 형식을 지켜야**한다. -- 기능 구현을 완료한 뒤 아래 가이드에 따라 테스트를 실행했을 때 모든 테스트가 성공하는지 확인한다. -- **테스트가 실패할 경우 0점으로 처리**되므로, 반드시 확인 후 제출한다. - - -### ~~테스트 실행 가이드~~ - -- ~~터미널에서 `java -version`을 실행하여 Java 버전이 11인지 확인한다. Eclipse 또는 IntelliJ IDEA와 같은 IDE에서 Java 11로 실행되는지 확인한다.~~ -- ~~터미널에서 Mac 또는 Linux 사용자의 경우 `./gradlew clean build` 명령을 실행하고, - Windows 사용자의 경우 `gradlew.bat clean test` 명령을 실행할 때 모든 테스트가 아래와 같이 통과하는지 확인한다.~~ - -``` -BUILD SUCCESSFUL in 0 -``` - ---- - -## 🚀 기능 요구 사항 - -로또 게임 기능을 구현해야 한다. 로또 게임은 아래와 같은 규칙으로 진행된다. - -``` -- 로또 번호의 숫자 범위는 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]"로 시작하는 에러 메시지를 출력 후 종료한다. - -### 입출력 요구 사항 - -#### 입력 - -- 로또 구입 금액을 입력 받는다. 구입 금액은 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%입니다. -``` - ---- - -## 🎯 프로그래밍 요구 사항 - -- JDK 11 버전에서 실행 가능해야 한다. **JDK 11에서 정상적으로 동작하지 않을 경우 0점 처리한다.** -- 프로그램 실행의 시작점은 `Application`의 `main()`이다. -- `build.gradle` 파일을 변경할 수 없고, 외부 라이브러리를 사용하지 않는다. -- [Java 코드 컨벤션](https://github.com/woowacourse/woowacourse-docs/tree/master/styleguide/java) 가이드를 준수하며 프로그래밍한다. -- 프로그램 종료 시 `System.exit()`를 호출하지 않는다. -- 프로그램 구현이 완료되면 `ApplicationTest`의 모든 테스트가 성공해야 한다. **테스트가 실패할 경우 0점 처리한다.** -- 프로그래밍 요구 사항에서 달리 명시하지 않는 한 파일, 패키지 이름을 수정하거나 이동하지 않는다. -- 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, Scanner) 로직은 제외한다. - - 핵심 로직을 구현하는 코드와 UI를 담당하는 로직을 분리해 구현한다. - - 단위 테스트 작성이 익숙하지 않다면 `test/java/lotto/LottoTest`를 참고하여 학습한 후 테스트를 구현한다. - -### 라이브러리 - -- [`camp.nextstep.edu.missionutils`](https://github.com/woowacourse-projects/mission-utils)에서 제공하는 `Randoms` 및 `Console` API를 사용하여 구현해야 한다. - - Random 값 추출은 `camp.nextstep.edu.missionutils.Randoms`의 `pickUniqueNumbersInRange()`를 활용한다. - - 사용자가 입력하는 값은 `camp.nextstep.edu.missionutils.Console`의 `readLine()`을 활용한다. - -#### 사용 예시 - -```java -List numbers = Randoms.pickUniqueNumbersInRange(1, 45, 6); -``` - -### Lotto 클래스 - -- 제공된 `Lotto` 클래스를 활용해 구현해야 한다. -- `Lotto`에 매개 변수가 없는 생성자를 추가할 수 없다. -- `numbers`의 접근 제어자인 private을 변경할 수 없다. -- `Lotto`에 필드(인스턴스 변수)를 추가할 수 없다. -- `Lotto`의 패키지 변경은 가능하다. - -```java -public class Lotto { - private final List numbers; - - public Lotto(List numbers) { - validate(numbers); - this.numbers = numbers; - } - - private void validate(List numbers) { - if (numbers.size() != 6) { - throw new IllegalArgumentException(); - } - } - - // TODO: 추가 기능 구현 -} -``` - ---- - -## ✏️ 과제 진행 요구 사항 - -- 미션은 [practice-oop-lotto](https://github.com/COW-edu/practice-oop-lotto) 저장소를 Fork & Clone해 시작한다. -- **기능을 구현하기 전 `docs/README.md`에 구현할 기능 목록을 정리**해 추가한다. -- **Git의 커밋 단위는 앞 단계에서 `docs/README.md`에 정리한 기능 목록 단위**로 추가한다. - - [커밋 메시지 컨벤션](https://gist.github.com/stephenparish/9941e89d80e2bc58a153) 가이드를 참고해 커밋 메시지를 작성한다. +# java-lotto-precourse +### 기능 구현 목록 + +- [ ] **로또 구입 금액 입력 기능** + - [ ] 사용자가 로또 구입 금액을 입력한다 + - [ ] 구입 금액이 1,000 단위로 나누어 떨어져야한다 +- [ ] **로또 번호 생성 기능** + - [ ] 사용자가 입력한 금액에 따라 로또 티켓 수량을 계산한다. + - [ ] 각 로또 티켓마다 1~45 사이의 중복되지 않는 6개의 번호를 생성한다. + - [ ] 로또 번호는 오름차순으로 정렬하여 생성한다. +- [ ] **로또 티켓 발행 및 출력 기능** + - [ ] 생성된 로또 티켓의 번호를 화면에 출력한다 + +예시: + + ``` + + 8개를 구매했습니다. + [8, 21, 23, 41, 42, 43] + [3, 5, 11, 16, 32, 38] + ... + + ``` + +- [x] **당첨 번호 입력 기능** + - [x] 사용자가 당첨 번호 6개를 입력하게 한다 + - [x] 입력된 당첨 번호가 1~45 사이의 숫자로 이루어져 있는지 검증한다 + - [x] 중복되지 않는 번호만 입력받도록 유효성을 검사한다. +- [x] **보너스 번호 입력 기능** + - [x] 사용자가 보너스 번호 1개를 입력하도록 한다. + - [x] 입력된 보너스 번호가 1~45 사이의 숫자인지 검증한다 + - [x] 당첨 번호와 중복되지 않는지를 검증한다 +- [x] **로또 당첨 결과 계산 기능** + - [x] 사용자가 구매한 각 로또 티켓과 당첨 번호를 비교하여 등수를 계산한다 + + 당첨 기준: + + - **1등**: 6개 번호 일치 + - **2등**: 5개 번호 + 보너스 번호 일치 + - **3등**: 5개 번호 일치 + - **4등**: 4개 번호 일치 + - **5등**: 3개 번호 일치 + - **꽝**: 2개 이하 번호 일치 +- [x] **수익률 계산 기능** + - [x] 사용자가 입력한 금액과 당첨금액을 바탕으로 수익률을 계산한다 + - [x] 수익률을 소수점 둘째 자리에서 반올림하여 출력한다 + +예시: + + ``` + + 총 수익률은 62.5%입니다. + + ``` + +- [x] **당첨 결과 및 수익률 출력 기능** + - [x] 당첨 결과를 화면에 출력한다. + - [x] 수익률을 화면에 출력한다 + +예시: + + ``` + 복사 + 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%입니다. + + ``` + + +### 에외처리 + +- [x] **구입 금액 입력 오류** + - [x] 입력금액이 1,000원 단위가 아닐경우 + - [x] 입력금액이 숫자가 아닌 경우 +- [x] **당첨 번호 입력 오류** + - [x] 중복된 번호가 있는경우 + - [x] 1~45 사이의 숫자가 아닐 경우 +- [x] **보너스 번호 입력오류** + - [x] 당첨 번호와 중복될 경우 + - [x] 1~45 사이의 숫자가 아닐 경우 + - [x] 보너스 번호를 2개이상 입력한 경우 \ No newline at end of file diff --git a/build.gradle b/build.gradle index 9d087b14..ee0f309f 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,7 @@ dependencies { java { toolchain { - languageVersion = JavaLanguageVersion.of(11) + languageVersion = JavaLanguageVersion.of(17) } } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c0..a4b76b95 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 28ff446a..9355b415 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c..f5feea6d 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,69 +15,104 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +122,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd32..9d21a218 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/java/lotto/Application.java b/src/main/java/lotto/Application.java index d190922b..c9d44bda 100644 --- a/src/main/java/lotto/Application.java +++ b/src/main/java/lotto/Application.java @@ -1,7 +1,12 @@ package lotto; +import lotto.adapter.in.console.ConsoleLottoController; +import lotto.config.AppConfig; + public class Application { public static void main(String[] args) { - // TODO: 프로그램 구현 + AppConfig config = new AppConfig(); + ConsoleLottoController controller = config.consoleLottoController(); + controller.run(); } } diff --git a/src/main/java/lotto/Lotto.java b/src/main/java/lotto/Lotto.java deleted file mode 100644 index 519793d1..00000000 --- a/src/main/java/lotto/Lotto.java +++ /dev/null @@ -1,20 +0,0 @@ -package lotto; - -import java.util.List; - -public class Lotto { - private final List numbers; - - public Lotto(List numbers) { - validate(numbers); - this.numbers = numbers; - } - - private void validate(List numbers) { - if (numbers.size() != 6) { - throw new IllegalArgumentException(); - } - } - - // TODO: 추가 기능 구현 -} diff --git a/src/main/java/lotto/adapter/in/console/ConsoleInputView.java b/src/main/java/lotto/adapter/in/console/ConsoleInputView.java new file mode 100644 index 00000000..38a96af2 --- /dev/null +++ b/src/main/java/lotto/adapter/in/console/ConsoleInputView.java @@ -0,0 +1,24 @@ +package lotto.adapter.in.console; + +import camp.nextstep.edu.missionutils.Console; + +public class ConsoleInputView { + private static final String PURCHASE_AMOUNT_PROMPT = "구입 금액을 입력해 주세요."; + private static final String WINNING_NUMBERS_PROMPT = "\n당첨 번호를 입력해 주세요 (쉼표로 구분)."; + private static final String BONUS_NUMBER_PROMPT = "\n보너스 번호를 입력해 주세요."; + + public String inputPurchaseAmount() { + System.out.println(PURCHASE_AMOUNT_PROMPT); + return Console.readLine().trim(); + } + + public String inputWinningNumbers() { + System.out.println(WINNING_NUMBERS_PROMPT); + return Console.readLine().trim(); + } + + public String inputBonusNumber() { + System.out.println(BONUS_NUMBER_PROMPT); + return Console.readLine().trim(); + } +} diff --git a/src/main/java/lotto/adapter/in/console/ConsoleLottoController.java b/src/main/java/lotto/adapter/in/console/ConsoleLottoController.java new file mode 100644 index 00000000..588ba926 --- /dev/null +++ b/src/main/java/lotto/adapter/in/console/ConsoleLottoController.java @@ -0,0 +1,47 @@ +package lotto.adapter.in.console; + +import lotto.application.dto.LottoResultDTO; +import lotto.application.validation.NumberListValidation; +import lotto.application.validation.NumberValidation; +import lotto.domain.model.LottoTickets; +import lotto.domain.model.WinningLotto; +import lotto.domain.port.in.LottoUseCase; + +import java.util.List; + +public class ConsoleLottoController { + private final ConsoleInputView inputView; + private final ConsoleOutputView outputView; + private final LottoUseCase lottoUseCase; + private final NumberValidation amountValidator; + private final NumberListValidation numberListValidator; + private final NumberValidation bonusValidator; + + public ConsoleLottoController(ConsoleInputView inputView, ConsoleOutputView outputView, LottoUseCase lottoUseCase, NumberValidation amountValidator, NumberListValidation numberListValidator, NumberValidation bonusValidator) { + this.inputView = inputView; + this.outputView = outputView; + this.lottoUseCase = lottoUseCase; + this.amountValidator = amountValidator; + this.numberListValidator = numberListValidator; + this.bonusValidator = bonusValidator; + } + + public void run() { + try { + int amount = amountValidator.validate(inputView.inputPurchaseAmount()); + lottoUseCase.purchase(amount); + LottoTickets tickets = lottoUseCase.getLottoTickets(); + outputView.printLottoTickets(tickets); + + List winningNumbers = numberListValidator.validate(inputView.inputWinningNumbers()); + int bonusNumber = bonusValidator.validate(inputView.inputBonusNumber()); + WinningLotto winningLotto = new WinningLotto(winningNumbers, bonusNumber); + + LottoResultDTO resultDTO = lottoUseCase.checkWinning(tickets, winningLotto, amount); + outputView.printStatistics(resultDTO.getResult(), resultDTO.getProfitRate()); + + }catch (IllegalArgumentException e){ + outputView.printError(e.getMessage()); + } + } +} diff --git a/src/main/java/lotto/adapter/in/console/ConsoleOutputView.java b/src/main/java/lotto/adapter/in/console/ConsoleOutputView.java new file mode 100644 index 00000000..578d6ca8 --- /dev/null +++ b/src/main/java/lotto/adapter/in/console/ConsoleOutputView.java @@ -0,0 +1,43 @@ +package lotto.adapter.in.console; + +import lotto.domain.model.Lotto; +import lotto.domain.model.LottoRank; +import lotto.domain.model.LottoResult; +import lotto.domain.model.LottoTickets; +import lotto.util.LottoFormatter; + +import java.util.Arrays; +import java.util.List; + +public class ConsoleOutputView { + private static final String PURCHASED_TICKETS_MESSAGE = "\n%d개를 구매했습니다."; + private static final String WINNING_STATISTICS_TITLE = "\n당첨 통계"; + private static final String SEPARATOR_LINE = "---"; + + public void printLottoTickets(LottoTickets lootoTickets){ + System.out.printf((PURCHASED_TICKETS_MESSAGE) + "%n", lootoTickets.size()); + List tickets = lootoTickets.getTickets(); + for (Lotto ticket : tickets) { + System.out.println(ticket.getNumbers()); + } + } + + public void printStatistics(LottoResult result, double profitRate) { + System.out.println(WINNING_STATISTICS_TITLE); + System.out.println(SEPARATOR_LINE); + + Arrays.stream(LottoRank.values()) + .filter(rank -> rank != LottoRank.NONE) + .forEach(rank -> { + String rankResult = LottoFormatter.formatRankResult(rank, result.getCountByRank(rank)); + System.out.println(rankResult); + }); + + String formattedProfitRate = LottoFormatter.formatProfitRate(profitRate); + System.out.println(formattedProfitRate); + } + + public void printError(String message) { + System.out.println(message); + } +} diff --git a/src/main/java/lotto/adapter/out/memory/LottoRepository.java b/src/main/java/lotto/adapter/out/memory/LottoRepository.java new file mode 100644 index 00000000..d162c78c --- /dev/null +++ b/src/main/java/lotto/adapter/out/memory/LottoRepository.java @@ -0,0 +1,18 @@ +package lotto.adapter.out.memory; + +import lotto.domain.model.LottoTickets; +import lotto.domain.port.out.LottoRepositoryPort; + +public class LottoRepository implements LottoRepositoryPort { + private LottoTickets tickets; + + @Override + public void save(LottoTickets tickets) { + this.tickets = tickets; + } + + @Override + public LottoTickets findAll() { + return tickets; + } +} diff --git a/src/main/java/lotto/application/dto/LottoResultDTO.java b/src/main/java/lotto/application/dto/LottoResultDTO.java new file mode 100644 index 00000000..9f1b9fac --- /dev/null +++ b/src/main/java/lotto/application/dto/LottoResultDTO.java @@ -0,0 +1,21 @@ +package lotto.application.dto; + +import lotto.domain.model.LottoResult; + +public class LottoResultDTO { + private final LottoResult result; + private final double profitRate; + + public LottoResultDTO(LottoResult result, double profitRate) { + this.result = result; + this.profitRate = profitRate; + } + + public LottoResult getResult() { + return result; + } + + public double getProfitRate() { + return profitRate; + } +} diff --git a/src/main/java/lotto/application/service/LottoService.java b/src/main/java/lotto/application/service/LottoService.java new file mode 100644 index 00000000..58a70a82 --- /dev/null +++ b/src/main/java/lotto/application/service/LottoService.java @@ -0,0 +1,40 @@ +package lotto.application.service; + + +import lotto.application.dto.LottoResultDTO; +import lotto.domain.generator.LottoNumberGenerator; +import lotto.domain.model.*; +import lotto.domain.port.in.LottoUseCase; +import lotto.domain.port.out.LottoRepositoryPort; + +public class LottoService implements LottoUseCase { + + private final LottoRepositoryPort repository; + private final LottoNumberGenerator generator; + private final ResultCalculator resultCalculator; + + public LottoService(LottoRepositoryPort repository, LottoNumberGenerator generator, ResultCalculator resultCalculator) { + this.repository = repository; + this.generator = generator; + this.resultCalculator = resultCalculator; + } + + @Override + public void purchase(int amount) { + LottoTickets tickets = LottoTickets.fromAmount(amount, generator); + repository.save(tickets); + } + + @Override + public LottoTickets getLottoTickets() { + return repository.findAll(); + } + + @Override + public LottoResultDTO checkWinning(LottoTickets tickets, WinningLotto winningLotto, int amount) { + LottoResult result = resultCalculator.calculate(tickets, winningLotto); + double profitRate = ProfitCalculator.calculateProfitRate(result.getResults(), amount); + return new LottoResultDTO(result, profitRate); + } + +} diff --git a/src/main/java/lotto/application/validation/AmountValidator.java b/src/main/java/lotto/application/validation/AmountValidator.java new file mode 100644 index 00000000..5f248be8 --- /dev/null +++ b/src/main/java/lotto/application/validation/AmountValidator.java @@ -0,0 +1,18 @@ +package lotto.application.validation; + +import lotto.util.ErrorMessages; + +public class AmountValidator implements NumberValidation { + @Override + public int validate(String input) { + return validateAndParseAmount(input); + } + + private int validateAndParseAmount(String amountInput) { + try { + return Integer.parseInt(amountInput); + }catch (NumberFormatException e){ + throw new IllegalArgumentException(ErrorMessages.INVALID_AMOUNT_FORMAT); + } + } +} diff --git a/src/main/java/lotto/application/validation/BonusNumberValidator.java b/src/main/java/lotto/application/validation/BonusNumberValidator.java new file mode 100644 index 00000000..b6c6dbce --- /dev/null +++ b/src/main/java/lotto/application/validation/BonusNumberValidator.java @@ -0,0 +1,18 @@ +package lotto.application.validation; + +import lotto.util.ErrorMessages; + +public class BonusNumberValidator implements NumberValidation { + @Override + public int validate(String input) { + return parseNumber(input); + } + + private int parseNumber(String input) { + try { + return Integer.parseInt(input.trim()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ErrorMessages.INVALID_NUMBER_INPUT); + } + } +} diff --git a/src/main/java/lotto/application/validation/LottoNumberValidator.java b/src/main/java/lotto/application/validation/LottoNumberValidator.java new file mode 100644 index 00000000..78b95af2 --- /dev/null +++ b/src/main/java/lotto/application/validation/LottoNumberValidator.java @@ -0,0 +1,26 @@ +package lotto.application.validation; + +import lotto.util.ErrorMessages; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class LottoNumberValidator implements NumberListValidation { + + @Override + public List validate(String input) { + return parseNumbers(input); + } + + private List parseNumbers(String input) { + try { + return Arrays.stream(input.split(",")) + .map(String::trim) + .map(Integer::parseInt) + .collect(Collectors.toList()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ErrorMessages.INVALID_NUMBER_INPUT); + } + } +} diff --git a/src/main/java/lotto/application/validation/NumberListValidation.java b/src/main/java/lotto/application/validation/NumberListValidation.java new file mode 100644 index 00000000..4e3907de --- /dev/null +++ b/src/main/java/lotto/application/validation/NumberListValidation.java @@ -0,0 +1,7 @@ +package lotto.application.validation; + +import java.util.List; + +public interface NumberListValidation { + List validate(T input); +} diff --git a/src/main/java/lotto/application/validation/NumberValidation.java b/src/main/java/lotto/application/validation/NumberValidation.java new file mode 100644 index 00000000..dee668e4 --- /dev/null +++ b/src/main/java/lotto/application/validation/NumberValidation.java @@ -0,0 +1,5 @@ +package lotto.application.validation; + +public interface NumberValidation { + int validate(T input); +} diff --git a/src/main/java/lotto/config/AppConfig.java b/src/main/java/lotto/config/AppConfig.java new file mode 100644 index 00000000..4a467f88 --- /dev/null +++ b/src/main/java/lotto/config/AppConfig.java @@ -0,0 +1,63 @@ +package lotto.config; + +import lotto.adapter.in.console.ConsoleInputView; +import lotto.adapter.in.console.ConsoleLottoController; +import lotto.adapter.in.console.ConsoleOutputView; +import lotto.adapter.out.memory.LottoRepository; +import lotto.application.service.LottoService; +import lotto.application.validation.*; +import lotto.domain.generator.LottoNumberGenerator; +import lotto.domain.generator.LottoNumberGeneratorImpl; +import lotto.domain.model.ResultCalculator; +import lotto.domain.port.in.LottoUseCase; +import lotto.domain.port.out.LottoRepositoryPort; + +public class AppConfig { + + public ConsoleInputView consoleInputView() { + return new ConsoleInputView(); + } + + public ConsoleOutputView consoleOutputView() { + return new ConsoleOutputView(); + } + + public NumberValidation amountValidator() { + return new AmountValidator(); + } + + public NumberValidation bonusNumberValidator() { + return new BonusNumberValidator(); + } + + public NumberListValidation lottoNumberValidator() { + return new LottoNumberValidator(); + } + + public LottoRepositoryPort lottoRepository() { + return new LottoRepository(); + } + + public LottoNumberGenerator lottoNumberGenerator() { + return new LottoNumberGeneratorImpl(); + } + + public ResultCalculator resultCalculator() { + return new ResultCalculator(); + } + + public LottoUseCase lottoUseCase() { + return new LottoService(lottoRepository(), lottoNumberGenerator(), resultCalculator()); + } + + public ConsoleLottoController consoleLottoController() { + return new ConsoleLottoController( + consoleInputView(), + consoleOutputView(), + lottoUseCase(), + amountValidator(), + lottoNumberValidator(), + bonusNumberValidator() + ); + } +} diff --git a/src/main/java/lotto/domain/generator/LottoNumberGenerator.java b/src/main/java/lotto/domain/generator/LottoNumberGenerator.java new file mode 100644 index 00000000..00a085f3 --- /dev/null +++ b/src/main/java/lotto/domain/generator/LottoNumberGenerator.java @@ -0,0 +1,7 @@ +package lotto.domain.generator; + +import java.util.List; + +public interface LottoNumberGenerator { + List generate(); +} diff --git a/src/main/java/lotto/domain/generator/LottoNumberGeneratorImpl.java b/src/main/java/lotto/domain/generator/LottoNumberGeneratorImpl.java new file mode 100644 index 00000000..e447324d --- /dev/null +++ b/src/main/java/lotto/domain/generator/LottoNumberGeneratorImpl.java @@ -0,0 +1,14 @@ +package lotto.domain.generator; + +import camp.nextstep.edu.missionutils.Randoms; +import lotto.util.LottoConstants; + +import java.util.List; + +public class LottoNumberGeneratorImpl implements LottoNumberGenerator { + + @Override + public List generate() { + return Randoms.pickUniqueNumbersInRange(LottoConstants.MIN_LOTTO_NUMBER, LottoConstants.MAX_LOTTO_NUMBER, LottoConstants.LOTTO_NUMBER_COUNT); + } +} diff --git a/src/main/java/lotto/domain/model/Lotto.java b/src/main/java/lotto/domain/model/Lotto.java new file mode 100644 index 00000000..ac823713 --- /dev/null +++ b/src/main/java/lotto/domain/model/Lotto.java @@ -0,0 +1,39 @@ +package lotto.domain.model; + +import lotto.util.ErrorMessages; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Lotto { + private final List numbers; + + public Lotto(List numbers) { + validate(numbers); + validateNumberRange(numbers); + validateDuplication(numbers); + this.numbers = numbers; + } + + private void validate(List numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException(ErrorMessages.INVALID_LOTTO_NUMBER_COUNT); + } + } + private void validateNumberRange(List numbers) { + if (numbers.stream().anyMatch(num -> num < 1 || num > 45)) { + throw new IllegalArgumentException(ErrorMessages.INVALID_LOTTO_NUMBER_RANGE); + } + } + + private void validateDuplication(List numbers) { + Set uniqueNumbers = new HashSet<>(numbers); + if (uniqueNumbers.size() != numbers.size()) { + throw new IllegalArgumentException(ErrorMessages.DUPLICATE_LOTTO_NUMBER); + } + } + public List getNumbers() { + return numbers; + } +} diff --git a/src/main/java/lotto/domain/model/LottoRank.java b/src/main/java/lotto/domain/model/LottoRank.java new file mode 100644 index 00000000..7f473233 --- /dev/null +++ b/src/main/java/lotto/domain/model/LottoRank.java @@ -0,0 +1,50 @@ +package lotto.domain.model; + +public enum LottoRank { + FIRST(6, false, 2_000_000_000, "6개 일치"), + SECOND(5, true, 30_000_000, "5개 일치, 보너스 볼 일치"), + THIRD(5, false, 1_500_000, "5개 일치"), + FOURTH(4, false, 50_000, "4개 일치"), + FIFTH(3, false, 5_000, "3개 일치"), + NONE(0, false, 0, ""); + + private final int matchCount; + private final boolean matchBonus; + private final int prize; + private final String description; + + LottoRank(int matchCount, boolean matchBonus, int prize, String description) { + this.matchCount = matchCount; + this.matchBonus = matchBonus; + this.prize = prize; + this.description = description; + } + + public static LottoRank valueOf(int matchCount, boolean matchBonus) { + return java.util.Arrays.stream(values()) + .filter(rank -> rank.matchCount == matchCount && rank.matchBonus == matchBonus) + .findFirst() + .orElse(getRankByMatchCount(matchCount)); + } + + private static LottoRank getRankByMatchCount(int matchCount) { + if (matchCount == 5) { + return THIRD; + } + if (matchCount == 4) { + return FOURTH; + } + if (matchCount == 3) { + return FIFTH; + } + return NONE; + } + + public int getPrize() { + return prize; + } + + public String getDescription() { + return description; + } +} diff --git a/src/main/java/lotto/domain/model/LottoResult.java b/src/main/java/lotto/domain/model/LottoResult.java new file mode 100644 index 00000000..dd05e6ca --- /dev/null +++ b/src/main/java/lotto/domain/model/LottoResult.java @@ -0,0 +1,23 @@ +package lotto.domain.model; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.Map; + +public class LottoResult { + private final Map results = new EnumMap<>(LottoRank.class); + + public LottoResult(Map results) { + for (LottoRank rank : LottoRank.values()) { + this.results.put(rank, results.getOrDefault(rank, 0)); + } + } + + public Map getResults() { + return Collections.unmodifiableMap(results); + } + + public int getCountByRank(LottoRank rank) { + return results.getOrDefault(rank, 0); + } +} diff --git a/src/main/java/lotto/domain/model/LottoTickets.java b/src/main/java/lotto/domain/model/LottoTickets.java new file mode 100644 index 00000000..4883796d --- /dev/null +++ b/src/main/java/lotto/domain/model/LottoTickets.java @@ -0,0 +1,51 @@ +package lotto.domain.model; + +import lotto.domain.generator.LottoNumberGenerator; +import lotto.util.ErrorMessages; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class LottoTickets { + private static final int PRICE_PER_TICKET = 1000; + + private final List tickets; + + public static LottoTickets fromAmount(int amount, LottoNumberGenerator generator) { + validateAmount(amount); + int count = amount / PRICE_PER_TICKET; + List generated = new ArrayList<>(); + for (int i = 0; i < count; i++) { + List sortedNumbers = generator.generate().stream() + .sorted() + .collect(Collectors.toList()); + generated.add(new Lotto(sortedNumbers)); + } + return new LottoTickets(generated); + } + + private LottoTickets(List tickets) { + validateEmpty(tickets); + this.tickets = List.copyOf(tickets); + } + + private void validateEmpty(List tickets) { + if (tickets == null || tickets.isEmpty()) { + throw new IllegalArgumentException(ErrorMessages.EMPTY_LOTTO_TICKET_LIST); + } + } + + private static void validateAmount(int amount) { + if (amount <= 0 || amount % PRICE_PER_TICKET != 0) { + throw new IllegalArgumentException(ErrorMessages.INVALID_PURCHASE_AMOUNT); + } + } + + public List getTickets() { + return tickets; + } + + public int size() { + return tickets.size(); + } +} \ No newline at end of file diff --git a/src/main/java/lotto/domain/model/ProfitCalculator.java b/src/main/java/lotto/domain/model/ProfitCalculator.java new file mode 100644 index 00000000..cfa81e49 --- /dev/null +++ b/src/main/java/lotto/domain/model/ProfitCalculator.java @@ -0,0 +1,14 @@ +package lotto.domain.model; + +import java.util.Map; + +public class ProfitCalculator { + private static final int PERCENTAGE_MULTIPLIER = 100; + + public static double calculateProfitRate(Map results, int amountSpent) { + double totalProfit = results.entrySet().stream() + .mapToDouble(entry -> entry.getKey().getPrize() * entry.getValue()) + .sum(); + return (totalProfit / amountSpent) * PERCENTAGE_MULTIPLIER; + } +} diff --git a/src/main/java/lotto/domain/model/ResultCalculator.java b/src/main/java/lotto/domain/model/ResultCalculator.java new file mode 100644 index 00000000..ba7de4ab --- /dev/null +++ b/src/main/java/lotto/domain/model/ResultCalculator.java @@ -0,0 +1,27 @@ +package lotto.domain.model; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class ResultCalculator { + public LottoResult calculate(LottoTickets tickets, WinningLotto winningLotto) { + Map resultMap = new EnumMap<>(LottoRank.class); + + for (Lotto ticket : tickets.getTickets()) { + int matchCount = countMatchingNumbers(ticket.getNumbers(), winningLotto.getWinningNumbers()); + boolean bonusMatch = ticket.getNumbers().contains(winningLotto.getBonusNumber()); + + LottoRank rank = LottoRank.valueOf(matchCount, bonusMatch); // 등수 계산 + resultMap.put(rank, resultMap.getOrDefault(rank, 0) + 1); // 등수별 누적 카운트 + } + + return new LottoResult(resultMap); + } + + private int countMatchingNumbers(List userNumbers, List winningNumbers) { + return (int) userNumbers.stream() + .filter(winningNumbers::contains) + .count(); + } +} diff --git a/src/main/java/lotto/domain/model/WinningLotto.java b/src/main/java/lotto/domain/model/WinningLotto.java new file mode 100644 index 00000000..a9c38319 --- /dev/null +++ b/src/main/java/lotto/domain/model/WinningLotto.java @@ -0,0 +1,50 @@ +package lotto.domain.model; + +import lotto.util.ErrorMessages; +import lotto.util.LottoConstants; + +import java.util.HashSet; +import java.util.List; + +public class WinningLotto { + + private final List winningNumbers; + private final int bonusNumber; + + public WinningLotto(List winningNumbers, int bonusNumber) { + validateWinningNumbers(winningNumbers); + validateBonusNumber(winningNumbers, bonusNumber); + this.winningNumbers = winningNumbers; + this.bonusNumber = bonusNumber; + } + + private void validateWinningNumbers(List numbers) { + if (numbers.size() != LottoConstants.LOTTO_NUMBER_COUNT) { + throw new IllegalArgumentException(ErrorMessages.INVALID_LOTTO_NUMBER_COUNT); + } + if (new HashSet<>(numbers).size() != LottoConstants.LOTTO_NUMBER_COUNT) { + throw new IllegalArgumentException(ErrorMessages.DUPLICATE_LOTTO_NUMBER); + } + if (numbers.stream().anyMatch(n -> n < LottoConstants.MIN_LOTTO_NUMBER || n > LottoConstants.MAX_LOTTO_NUMBER)) { + throw new IllegalArgumentException(ErrorMessages.INVALID_LOTTO_NUMBER_RANGE); + } + } + + private void validateBonusNumber(List winningNumbers, int bonus) { + if (bonus < LottoConstants.MIN_LOTTO_NUMBER || bonus > LottoConstants.MAX_LOTTO_NUMBER) { + throw new IllegalArgumentException(ErrorMessages.INVALID_LOTTO_NUMBER_RANGE); + } + if (winningNumbers.contains(bonus)) { + throw new IllegalArgumentException(ErrorMessages.DUPLICATE_BONUS_NUMBER); + } + } + + public List getWinningNumbers() { + return winningNumbers; + } + + public int getBonusNumber() { + return bonusNumber; + } + +} \ No newline at end of file diff --git a/src/main/java/lotto/domain/port/in/LottoUseCase.java b/src/main/java/lotto/domain/port/in/LottoUseCase.java new file mode 100644 index 00000000..c6477074 --- /dev/null +++ b/src/main/java/lotto/domain/port/in/LottoUseCase.java @@ -0,0 +1,12 @@ +package lotto.domain.port.in; + +import lotto.application.dto.LottoResultDTO; +import lotto.domain.model.LottoTickets; +import lotto.domain.model.WinningLotto; + +public interface LottoUseCase { + void purchase(int amount); + LottoTickets getLottoTickets(); + + LottoResultDTO checkWinning(LottoTickets tickets, WinningLotto winningLotto, int amount); +} diff --git a/src/main/java/lotto/domain/port/out/LottoRepositoryPort.java b/src/main/java/lotto/domain/port/out/LottoRepositoryPort.java new file mode 100644 index 00000000..468a7781 --- /dev/null +++ b/src/main/java/lotto/domain/port/out/LottoRepositoryPort.java @@ -0,0 +1,8 @@ +package lotto.domain.port.out; + +import lotto.domain.model.LottoTickets; + +public interface LottoRepositoryPort { + void save(LottoTickets tickets); + LottoTickets findAll(); +} diff --git a/src/main/java/lotto/util/ErrorMessages.java b/src/main/java/lotto/util/ErrorMessages.java new file mode 100644 index 00000000..6a466628 --- /dev/null +++ b/src/main/java/lotto/util/ErrorMessages.java @@ -0,0 +1,17 @@ +package lotto.util; + +public class ErrorMessages { + private static final String ERROR_PREFIX = "[ERROR] "; + + public static final String INVALID_LOTTO_NUMBER_COUNT = ERROR_PREFIX + "로또 번호는 6개여야 합니다."; + public static final String DUPLICATE_LOTTO_NUMBER = ERROR_PREFIX + "로또 번호는 중복될 수 없습니다."; + public static final String INVALID_LOTTO_NUMBER_RANGE = ERROR_PREFIX + "로또 번호는 1부터 45 사이의 숫자여야 합니다."; + public static final String INVALID_PURCHASE_AMOUNT = ERROR_PREFIX + "금액은 1,000원 단위여야 합니다."; + public static final String EMPTY_LOTTO_TICKET_LIST = ERROR_PREFIX + "구매한 로또 티켓 목록은 비어 있을 수 없습니다."; + public static final String INVALID_AMOUNT_FORMAT = ERROR_PREFIX + "구입 금액은 숫자여야 합니다."; + public static final String DUPLICATE_BONUS_NUMBER = ERROR_PREFIX + "보너스 번호는 당첨 번호와 중복될 수 없습니다."; + public static final String INVALID_NUMBER_INPUT = ERROR_PREFIX + "입력값은 숫자여야 합니다."; + + private ErrorMessages() { + } +} diff --git a/src/main/java/lotto/util/LottoConstants.java b/src/main/java/lotto/util/LottoConstants.java new file mode 100644 index 00000000..820781fd --- /dev/null +++ b/src/main/java/lotto/util/LottoConstants.java @@ -0,0 +1,10 @@ +package lotto.util; + +public class LottoConstants { + public static final int LOTTO_NUMBER_COUNT = 6; + public static final int MIN_LOTTO_NUMBER = 1; + public static final int MAX_LOTTO_NUMBER = 45; + + private LottoConstants() { + } +} diff --git a/src/main/java/lotto/util/LottoFormatter.java b/src/main/java/lotto/util/LottoFormatter.java new file mode 100644 index 00000000..dd25c81d --- /dev/null +++ b/src/main/java/lotto/util/LottoFormatter.java @@ -0,0 +1,20 @@ +package lotto.util; + +import lotto.domain.model.LottoRank; + +import java.text.NumberFormat; + +public class LottoFormatter { + private static final String RANK_RESULT_FORMAT = "%s (%s원) - %d개"; + private static final String TOTAL_PROFIT_MESSAGE = "총 수익률은 %.1f%%입니다."; + + + public static String formatRankResult(LottoRank rank, int count) { + String formattedPrize = NumberFormat.getInstance().format(rank.getPrize()); + return String.format(RANK_RESULT_FORMAT, rank.getDescription(), formattedPrize, count); + } + + public static String formatProfitRate(double profitRate) { + return String.format(TOTAL_PROFIT_MESSAGE, profitRate); + } +} diff --git a/src/test/java/lotto/LottoTest.java b/src/test/java/lotto/LottoTest.java index 0f3af0f6..e59ee676 100644 --- a/src/test/java/lotto/LottoTest.java +++ b/src/test/java/lotto/LottoTest.java @@ -1,5 +1,6 @@ package lotto; +import lotto.domain.model.Lotto; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test;