diff --git a/.gitignore b/.gitignore index 5dca701a77..0a0ce971c0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,35 +1,35 @@ -HELP.md -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/** -!**/src/test/** - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr -out/ - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ - -### VS Code ### -.vscode/ - -### Mac OS ### -.DS_Store +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store diff --git a/README.md b/README.md index 5fa2560b46..e995005d86 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -# java-lotto-precourse +# java-lotto-precourse diff --git a/build.gradle b/build.gradle index ae93bdf87f..c1cd8df4fa 100644 --- a/build.gradle +++ b/build.gradle @@ -1,25 +1,25 @@ -plugins { - id 'java' -} - -group = 'camp.nextstep.edu' -version = '1.0-SNAPSHOT' - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(21) - } -} - -repositories { - mavenCentral() - maven { url 'https://jitpack.io' } -} - -dependencies { - implementation 'com.github.woowacourse-projects:mission-utils:1.2.0' -} - -test { - useJUnitPlatform() -} +plugins { + id 'java' +} + +group = 'camp.nextstep.edu' +version = '1.0-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() + maven { url 'https://jitpack.io' } +} + +dependencies { + implementation 'com.github.woowacourse-projects:mission-utils:1.2.0' +} + +test { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37f853b1c8..7036d2e7d5 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,7 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index faf93008b7..ba132c9bba 100755 --- a/gradlew +++ b/gradlew @@ -1,251 +1,251 @@ -#!/bin/sh - -# -# 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. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# 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 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 -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 - -# 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\n' "$PWD" ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -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 ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -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 - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - 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" && ! "$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 - -# 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" || "$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 - 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 - # 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 -fi - - -# 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, 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" "$@" +#!/bin/sh + +# +# 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. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# 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 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 +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 + +# 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\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +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 ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + 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" && ! "$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 + +# 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" || "$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 + 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 + # 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 +fi + + +# 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, 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/settings.gradle b/settings.gradle index 364494c424..c7e6e3af86 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,4 @@ -plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' -} -rootProject.name = 'java-lotto' +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' +} +rootProject.name = 'java-lotto' diff --git a/src/main/java/Output/Formatter.java b/src/main/java/Output/Formatter.java new file mode 100644 index 0000000000..31a9e351df --- /dev/null +++ b/src/main/java/Output/Formatter.java @@ -0,0 +1,15 @@ +package Output; + +public class Formatter { + public static void printStatics(int correctNumber, boolean isBonus, int reward, int count){ + System.out.print(correctNumber+"개 일치"); + if(isBonus) { + System.out.print(", 보너스 볼 일치 "); + } + if(!isBonus){ + System.out.print(" "); + } + System.out.printf("(%,d원) - ", reward); + System.out.println(count +"개"); + } +} diff --git a/src/main/java/lotto/Application.java b/src/main/java/lotto/Application.java index d190922ba4..155d0ca846 100644 --- a/src/main/java/lotto/Application.java +++ b/src/main/java/lotto/Application.java @@ -1,7 +1,9 @@ -package lotto; - -public class Application { - public static void main(String[] args) { - // TODO: 프로그램 구현 - } -} +package lotto; + +public class Application { + public static void main(String[] args) { + + LottoController lottoController = new LottoController(); + lottoController.run(); + } +} diff --git a/src/main/java/lotto/Lotto.java b/src/main/java/lotto/Lotto.java index 88fc5cf12b..f8c09541f0 100644 --- a/src/main/java/lotto/Lotto.java +++ b/src/main/java/lotto/Lotto.java @@ -1,20 +1,41 @@ -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("[ERROR] 로또 번호는 6개여야 합니다."); - } - } - - // TODO: 추가 기능 구현 -} +package lotto; + +import java.util.Collections; +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); + unRepeatedNumber(numbers); + this.numbers = numbers; + } + + private void validate(List numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException("[ERROR] 로또 번호는 6개여야 합니다."); + } + } + + // 로또 번호 중복 여부 확인 + private void unRepeatedNumber(List numbers){ + Set nonRepeatedNumbers = new HashSet<>(numbers); + + if(nonRepeatedNumbers.size() != numbers.size()){ + throw new IllegalArgumentException("[ERROR] 중복된 당첨번호를 가질 수 없습니다."); + } + } + + public List getLotto(){ + return numbers; + } + + // 로또번호 정렬 + public void sortNumbers(){ + Collections.sort(numbers); + } + +} diff --git a/src/main/java/lotto/LottoController.java b/src/main/java/lotto/LottoController.java new file mode 100644 index 0000000000..95827f0c31 --- /dev/null +++ b/src/main/java/lotto/LottoController.java @@ -0,0 +1,68 @@ +package lotto; + +import Output.Formatter; +import camp.nextstep.edu.missionutils.Console; +import validator.Validator; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; +import java.util.Map; + +public class LottoController { + public void run(){ + // 입력1: 로또 구입 금액 + System.out.println("구입금액을 입력해 주세요."); + int purchasePrice = Validator.checkDivisibility(Console.readLine(), 1000); + + // 출력1: 발행 로또 수량 + int purchaseAmount = purchasePrice/1000; + System.out.printf("%d개를 구매했습니다.\n",purchaseAmount); + + // 로또 발행 + LottoService lottoService = new LottoService(purchaseAmount);//, winningNumbers, bonusNumber); + lottoService.issueLotto(); + + // 출력2: 발행 로또 번호 + for(int i=0; i winningNumbers = Validator.convertToList(Console.readLine(),","); + + // 입력3: 보너스 번호 + System.out.println("보너스 번호를 입력해 주세요."); + int bonusNumber = Validator.unRepeatedNumber(winningNumbers, Console.readLine()); + + // 당첨 번호 저장 + lottoService.setUpWinningLotto(winningNumbers, bonusNumber); + + // 출력3: 당첨 내역 + Map result = lottoService.saveLottoResult(); + + System.out.println("당첨 통계"); + System.out.println("---"); + + int winningPrize = 0; + for(Map.Entry entry:result.entrySet()){ + LottoResult key = entry.getKey(); + int count = entry.getValue(); + + if(key.getCorrectNumbers() == 0) continue; + Formatter.printStatics(key.getCorrectNumbers(), key.getBonus(), key.getReward(), count); + winningPrize += key.getReward() * entry.getValue(); + } + + // 출력4: 수익률 + float roi = (float) winningPrize /purchasePrice*100; + + // 소수점 둘째 자리 반올림 + BigDecimal bd = new BigDecimal(String.valueOf(roi)); + BigDecimal final_roi = bd.setScale(1, RoundingMode.HALF_UP); + System.out.printf("총 수익률은 %s%%입니다.%n",final_roi.toString()); + } +} diff --git a/src/main/java/lotto/LottoResult.java b/src/main/java/lotto/LottoResult.java new file mode 100644 index 0000000000..a82372a3c5 --- /dev/null +++ b/src/main/java/lotto/LottoResult.java @@ -0,0 +1,40 @@ +package lotto; + +public enum LottoResult { + NONE(0, false, 0), + FIFTH(3, false, 5000), + FOURTH(4, false, 50000), + THIRD(5, false, 1500000), + SECOND(5, true, 30000000 ), + FIRST(6, false, 2000000000); + + private final int correctNumbers; + private final boolean isBonus; + private final int reward; + + private LottoResult(int corNums, boolean isBonus, int reward){ + this.correctNumbers = corNums; + this.isBonus = isBonus; + this.reward = reward; + } + + public int getCorrectNumbers() { + return correctNumbers; + } + public boolean getBonus(){ return isBonus;} + public int getReward() { + return reward; + } + + public static LottoResult getResult(int corNums, boolean isBonus){ + for(LottoResult result:values()){ + if(result.getCorrectNumbers() != corNums){ + continue; + } + if(result.getCorrectNumbers() == 5 && result.isBonus == isBonus) return result; + //if(result.getCorrectNumbers() == 5 && result.isBonus != isBonus) return result; + if(result.getCorrectNumbers() != 5) return result; + } + return NONE; + } +} diff --git a/src/main/java/lotto/LottoService.java b/src/main/java/lotto/LottoService.java new file mode 100644 index 0000000000..4cf2813aac --- /dev/null +++ b/src/main/java/lotto/LottoService.java @@ -0,0 +1,74 @@ +package lotto; + +import camp.nextstep.edu.missionutils.Randoms; + +import java.util.*; + +public class LottoService { + private int purchaseAmount; + private Lotto winningLotto; + private List issueLottos; + private int bonusNumber; + private Map result; + + // 발행 로또 번호 객체 생성 + public LottoService(int pca){ + this.purchaseAmount = pca; + this.issueLottos = new ArrayList<>(); + } + + // 당첨 로또 번호 저장 + public void setUpWinningLotto(List list, int bonusNumber){ + this.winningLotto = new Lotto(list); + this.bonusNumber = bonusNumber; + } + + // 로또 발행 + public void issueLotto(){ + for(int i=0; i saveLottoResult(){ + result = new EnumMap<>(LottoResult.class); + + // Map 초기화 + for(LottoResult init:LottoResult.values()){ + result.put(init,0); + } + + for(Lotto lotto:issueLottos){ + int winningNumbers = confirmWinningNumbers(lotto); + boolean bonus = confirmWinningBonus(lotto); + + LottoResult lottoResult = LottoResult.getResult(winningNumbers, bonus); + result.compute(lottoResult, (k, prevResult) -> prevResult + 1); + } + return result; + } +} diff --git a/src/main/java/validator/Validator.java b/src/main/java/validator/Validator.java new file mode 100644 index 0000000000..491e84f0b4 --- /dev/null +++ b/src/main/java/validator/Validator.java @@ -0,0 +1,73 @@ +package validator; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Validator { + + // 1000원 단위로 나눠떨어지는지 확인 + public static int checkDivisibility(String number, int minUnit){ + + int amount = convertToNumber(number); + + if(amount % minUnit != 0){ + throw new IllegalArgumentException("[ERROR] 최소 입력 단위는 "+minUnit+"원입니다."); + } + return amount; + } + + // 숫자인지 확인 + public static int convertToNumber(String number){ + if(number.isEmpty() || number.trim().isEmpty()){ + throw new IllegalArgumentException("[ERROR] 빈 값을 입력할 수 없습니다."); + } + + try{ + return Integer.parseInt(number.trim()); + }catch(Exception e){ + throw new IllegalArgumentException("[ERROR] 숫자만 입력 가능합니다."); + } + } + + // 1~45 사이의 숫자인지 확인 + public static int convertToNumberInRange(int number){ + int MIN_VALUE = 1; + int MAX_VALUE = 45; + if(number < MIN_VALUE || number > MAX_VALUE){ + throw new IllegalArgumentException("[ERROR] "+MIN_VALUE+"~"+MAX_VALUE+"사이의 숫자만 입력 가능합니다."); + } + + return number; + } + + // 구분자 기준 숫자 리스트 변환 + public static List convertToList(String LottoNumbers,String separtor){ + + // 구분자 기준 분리 + String[] tempNums = LottoNumbers.split(separtor); + + // String[] → List로 변환 + List numberList = new ArrayList<>(); + for(String number:tempNums){ + int num = convertToNumberInRange(convertToNumber(number)); + numberList.add(num); + } + + if(numberList.size() != 6){ + throw new IllegalArgumentException("[ERROR] 로또 번호는 6개여야 합니다."); + } + return numberList; + } + + // 보너스 번호와 로또 번호 중복 여부 확인 + public static int unRepeatedNumber(List winningNumbers, String bonus){ + int bonusNumber = convertToNumber(bonus); + + if(winningNumbers.contains(bonusNumber)) { + throw new IllegalArgumentException("[ERROR] 보너스 번호는 당첨 번호와 일치할 수 없습니다."); + } + return bonusNumber; + } +} diff --git a/src/test/java/lotto/ApplicationTest.java b/src/test/java/lotto/ApplicationTest.java index a15c7d1f52..e2a4e1bb7a 100644 --- a/src/test/java/lotto/ApplicationTest.java +++ b/src/test/java/lotto/ApplicationTest.java @@ -1,61 +1,129 @@ -package lotto; - -import camp.nextstep.edu.missionutils.test.NsTest; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static camp.nextstep.edu.missionutils.test.Assertions.assertRandomUniqueNumbersInRangeTest; -import static camp.nextstep.edu.missionutils.test.Assertions.assertSimpleTest; -import static org.assertj.core.api.Assertions.assertThat; - -class ApplicationTest extends NsTest { - private static final String ERROR_MESSAGE = "[ERROR]"; - - @Test - void 기능_테스트() { - assertRandomUniqueNumbersInRangeTest( - () -> { - run("8000", "1,2,3,4,5,6", "7"); - assertThat(output()).contains( - "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개", - "총 수익률은 62.5%입니다." - ); - }, - List.of(8, 21, 23, 41, 42, 43), - List.of(3, 5, 11, 16, 32, 38), - List.of(7, 11, 16, 35, 36, 44), - List.of(1, 8, 11, 31, 41, 42), - List.of(13, 14, 16, 38, 42, 45), - List.of(7, 11, 30, 40, 42, 43), - List.of(2, 13, 22, 32, 38, 45), - List.of(1, 3, 5, 14, 22, 45) - ); - } - - @Test - void 예외_테스트() { - assertSimpleTest(() -> { - runException("1000j"); - assertThat(output()).contains(ERROR_MESSAGE); - }); - } - - @Override - public void runMain() { - Application.main(new String[]{}); - } -} +package lotto; + +import camp.nextstep.edu.missionutils.test.NsTest; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static camp.nextstep.edu.missionutils.test.Assertions.assertRandomUniqueNumbersInRangeTest; +import static camp.nextstep.edu.missionutils.test.Assertions.assertSimpleTest; +import static org.assertj.core.api.Assertions.assertThat; + +class ApplicationTest extends NsTest { + private static final String ERROR_MESSAGE = "[ERROR]"; + + @Test + void 기능_테스트() { + assertRandomUniqueNumbersInRangeTest( + () -> { + run("8000", "1,2,3,4,5,6", "7"); + assertThat(output()).contains( + "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개", + "총 수익률은 62.5%입니다." + ); + }, + List.of(8, 21, 23, 41, 42, 43), + List.of(3, 5, 11, 16, 32, 38), + List.of(7, 11, 16, 35, 36, 44), + List.of(1, 8, 11, 31, 41, 42), + List.of(13, 14, 16, 38, 42, 45), + List.of(7, 11, 30, 40, 42, 43), + List.of(2, 13, 22, 32, 38, 45), + List.of(1, 3, 5, 14, 22, 45) + ); + } + + @Test + void 기능_테스트_5개번호와_보너스번호_일치() { + assertRandomUniqueNumbersInRangeTest( + () -> { + run("8000", "8,21,23,41,42,45", "43"); + assertThat(output()).contains( + "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원) - 1개", + "6개 일치 (2,000,000,000원) - 0개", + "총 수익률은 375062.5%입니다." + ); + }, + List.of(8, 21, 23, 41, 42, 43), + List.of(3, 5, 11, 16, 32, 38), + List.of(7, 11, 16, 35, 36, 44), + List.of(1, 8, 11, 31, 41, 42), + List.of(13, 14, 16, 38, 42, 45), + List.of(7, 11, 30, 40, 42, 43), + List.of(2, 13, 22, 32, 38, 45), + List.of(1, 3, 5, 14, 22, 45) + ); + } + + @Test + void 기능_테스트_5개번호와_보너스번호_불일치() { + assertRandomUniqueNumbersInRangeTest( + () -> { + run("8000", "8,21,23,41,42,45", "40"); + assertThat(output()).contains( + "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원) - 1개", + "5개 일치, 보너스 볼 일치 (30,000,000원) - 0개", + "6개 일치 (2,000,000,000원) - 0개", + "총 수익률은 18812.5%입니다." + ); + }, + List.of(8, 21, 23, 41, 42, 43), + List.of(3, 5, 11, 16, 32, 38), + List.of(7, 11, 16, 35, 36, 44), + List.of(1, 8, 11, 31, 41, 42), + List.of(13, 14, 16, 38, 42, 45), + List.of(7, 11, 30, 40, 42, 43), + List.of(2, 13, 22, 32, 38, 45), + List.of(1, 3, 5, 14, 22, 45) + ); + } + + @Test + void 예외_테스트() { + assertSimpleTest(() -> { + runException("1000j"); + assertThat(output()).contains(ERROR_MESSAGE); + }); + } + + @Override + public void runMain() { + Application.main(new String[]{}); + } +} diff --git a/src/test/java/lotto/LottoTest.java b/src/test/java/lotto/LottoTest.java index 309f4e50ae..e4f856a042 100644 --- a/src/test/java/lotto/LottoTest.java +++ b/src/test/java/lotto/LottoTest.java @@ -1,25 +1,44 @@ -package lotto; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -class LottoTest { - @Test - void 로또_번호의_개수가_6개가_넘어가면_예외가_발생한다() { - assertThatThrownBy(() -> new Lotto(List.of(1, 2, 3, 4, 5, 6, 7))) - .isInstanceOf(IllegalArgumentException.class); - } - - @DisplayName("로또 번호에 중복된 숫자가 있으면 예외가 발생한다.") - @Test - void 로또_번호에_중복된_숫자가_있으면_예외가_발생한다() { - assertThatThrownBy(() -> new Lotto(List.of(1, 2, 3, 4, 5, 5))) - .isInstanceOf(IllegalArgumentException.class); - } - - // TODO: 추가 기능 구현에 따른 테스트 코드 작성 -} +package lotto; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import validator.Validator; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class LottoTest { + @Test + void 로또_번호의_개수가_6개가_넘어가면_예외가_발생한다() { + assertThatThrownBy(() -> new Lotto(List.of(1, 2, 3, 4, 5, 6, 7))) + .isInstanceOf(IllegalArgumentException.class); + } + + @DisplayName("로또 번호에 중복된 숫자가 있으면 예외가 발생한다.") + @Test + void 로또_번호에_중복된_숫자가_있으면_예외가_발생한다() { + assertThatThrownBy(() -> new Lotto(List.of(1, 2, 3, 4, 5, 5))) + .isInstanceOf(IllegalArgumentException.class); + } + + // TODO: 추가 기능 구현에 따른 테스트 코드 작성 + @DisplayName("보너스 번호가 로또 번호와 중복되면 예외가 발생한다.") + @Test + void checkBonusNumber_중복(){ + List winningNumbers = List.of(1, 2, 3, 4, 5, 6); + + assertThatThrownBy(() -> Validator.unRepeatedNumber(winningNumbers, "6")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("[ERROR] 보너스 번호는 당첨 번호와 일치할 수 없습니다."); + } + /* + @Test + void 당첨_번호_개수(){ + assertThat((new Lotto(List.of(1,2,3,4,5,6)) -> ) + + ); + } + */ +}