diff --git a/.gitignore b/.gitignore index 79c24b6f..424c4e0d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,118 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/macos,gradle,intellij,java +# Edit at https://www.toptal.com/developers/gitignore?templates=macos,gradle,intellij,java + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/ +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +### Java ### # Compiled class file *.class @@ -21,9 +136,37 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk -.idea/ -.idea/misc.xml ### Gradle ### .gradle **/build/ @@ -44,8 +187,4 @@ gradle-app.setting # JDT-specific (Eclipse Java Development Tools) .classpath -gradle -build.gradle -gradlew -gradlew.bat -settings.gradle +# End of https://www.toptal.com/developers/gitignore/api/macos,gradle,intellij,java \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..e8f3eac6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,20 @@ +plugins { + id 'java' +} + +group 'org.example' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.assertj:assertj-core:3.22.0' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..69a97150 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..744e882e --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or 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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# 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 +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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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" + which java >/dev/null 2>&1 || 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 + +# 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 +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 + +# 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 + # 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\"" + fi + i=`expr $i + 1` + 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" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "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. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +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. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..4c0cb4b1 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'java-lotto' diff --git a/src/main/java/com/lotto/App.java b/src/main/java/com/lotto/App.java index 74bc4b11..e89e5f04 100644 --- a/src/main/java/com/lotto/App.java +++ b/src/main/java/com/lotto/App.java @@ -1,4 +1,6 @@ -import controller.Controller; +package com.lotto; + +import com.lotto.controller.Controller; public class App { public static void main(String[] args) { diff --git a/src/main/java/com/lotto/controller/Controller.java b/src/main/java/com/lotto/controller/Controller.java index 7c4dbe15..fd5aa396 100644 --- a/src/main/java/com/lotto/controller/Controller.java +++ b/src/main/java/com/lotto/controller/Controller.java @@ -1,30 +1,84 @@ package com.lotto.controller; import java.util.List; -import java.util.Map; -import model.LottoService; -import model.LottoTickets; -import model.Rank; -import view.InputView; -import view.OutputView; +import com.lotto.model.LottoGame; +import com.lotto.model.LottoResult; +import com.lotto.model.LottoTickets; +import com.lotto.model.WinningLotto; +import com.lotto.util.ValidationUtil; +import com.lotto.view.InputView; +import com.lotto.view.OutputView; public class Controller { + private static final int TICKET_PRICE = 1_000; + private InputView inputView = new InputView(); + private OutputView outputView = new OutputView(); + private LottoGame lottoGame = new LottoGame(); + public void run() { - InputView inputView = new InputView(); - OutputView outputView = new OutputView(); - LottoService lottoService = new LottoService(); + inputView.initScanner(); + + int purchaseAmount = getPurchaseAmount(); + int manualCount = getManualCount(purchaseAmount); - int purchaseAmount = inputView.getPurchaseAmount(); - LottoTickets lottoTickets = lottoService.publishLottoTickets(purchaseAmount); + LottoTickets lottoTickets = getLottoTickets(purchaseAmount, manualCount); outputView.printTickets(lottoTickets); - //당첨 번호 입력 - List winningNumbers = inputView.getWinningNumbers(); - int bonusNumber = inputView.inputBonusNumber(); - Map result = lottoService.checkResult(lottoTickets, winningNumbers, bonusNumber); - double earningRate = lottoService.calculateEarningRate(purchaseAmount, result); + WinningLotto winningLotto = getWinningLotto(); + inputView.closeScanner(); + + LottoResult result = lottoGame.checkResult(lottoTickets, winningLotto); + double earningRate = lottoGame.calculateEarningRate(purchaseAmount, result); outputView.printResult(result, earningRate); } + + private Integer getPurchaseAmount() { + int purchaseAmount; + while (true) { + purchaseAmount = inputView.inputPurchaseAmount(); + if (purchaseAmount < TICKET_PRICE) { + System.out.printf("%s 이상의 금액을 입력해주세요.", TICKET_PRICE); + continue; + } + break; + } + return purchaseAmount; + } + + private int getManualCount(int purchaseAmount) { + int manualCount; + try { + manualCount = inputView.inputManualCount(); + ValidationUtil.validateManualCountRange(manualCount, purchaseAmount); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + manualCount = getManualCount(purchaseAmount); + } + return manualCount; + } + + private WinningLotto getWinningLotto() { + List winningNumbers = inputView.inputWinningNumbers(); + int bonusNumber = inputView.inputBonusNumber(winningNumbers); + WinningLotto winningLotto = new WinningLotto(winningNumbers, bonusNumber); + return winningLotto; + } + + private LottoTickets getLottoTickets(int purchaseAmount, int manualCount) { + int ticketCount = calculateTicketAmounts(purchaseAmount); + LottoTickets lottoTickets; + if (manualCount > 0) { + List> manualNumbers = inputView.inputManualNumbers(manualCount); + lottoTickets = new LottoTickets(ticketCount, manualNumbers); + } else { + lottoTickets = new LottoTickets(ticketCount); + } + return lottoTickets; + } + + private int calculateTicketAmounts(int purchaseAmount) { + return purchaseAmount / TICKET_PRICE; + } } diff --git a/src/main/java/com/lotto/model/LottoGame.java b/src/main/java/com/lotto/model/LottoGame.java new file mode 100644 index 00000000..8c203467 --- /dev/null +++ b/src/main/java/com/lotto/model/LottoGame.java @@ -0,0 +1,31 @@ +package com.lotto.model; + +import java.util.List; +import java.util.Map; + +public class LottoGame { + public LottoResult checkResult(LottoTickets tickets, WinningLotto winningNumbers) { + List ticketList = tickets.getTickets(); + LottoResult result = new LottoResult(); + + for (Lotto lotto : ticketList) { + int ticketResult = winningNumbers.compareTicket(lotto.getTicket()); + boolean bonusResult = winningNumbers.compareBonusNumber(lotto.getTicket()); + result.check(ticketResult, bonusResult); + } + return result; + } + + public double calculateEarningRate(int purchaseAmount, LottoResult result) { + + return (double)calculateWinningAmount(result.getResult()) / purchaseAmount * 100 - 100; + } + + private int calculateWinningAmount(Map result) { + int winningAmount = 0; + for (Rank rank : result.keySet()) { + winningAmount += result.get(rank) * rank.getWinningAmount(); + } + return winningAmount; + } +} diff --git a/src/main/java/com/lotto/model/LottoResult.java b/src/main/java/com/lotto/model/LottoResult.java new file mode 100644 index 00000000..795dabba --- /dev/null +++ b/src/main/java/com/lotto/model/LottoResult.java @@ -0,0 +1,29 @@ +package com.lotto.model; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +public class LottoResult { + private Map result = new LinkedHashMap<>(); + + public LottoResult() { + initResultMap(); + } + + public void check(int ticketResult, boolean bonusResult) { + if(ticketResult < 3) return; + Rank rank = Rank.checkRank(ticketResult, bonusResult); + result.put(rank, result.get(rank) + 1); + } + + public Map getResult() { + return Collections.unmodifiableMap(result); + } + + private void initResultMap() { + for (Rank rank : Rank.values()) { + result.put(rank, 0); + } + } +} diff --git a/src/main/java/com/lotto/model/LottoService.java b/src/main/java/com/lotto/model/LottoService.java deleted file mode 100644 index 71f776f3..00000000 --- a/src/main/java/com/lotto/model/LottoService.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.lotto.model; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -public class LottoService { - private static final int TICKET_PRICE = 1000; - - public LottoTickets publishLottoTickets(int purchaseAmount) { - int ticketCount = calculateAmount(purchaseAmount); - return LottoTickets.createLottoTickets(ticketCount); - } - - public Map checkResult(LottoTickets tickets, List winningNumbers, int bonusNumber) { - List ticketList = tickets.getTickets(); - - Map result = new LinkedHashMap<>() {{ - put(Rank.FIFTH, 0); - put(Rank.FOURTH, 0); - put(Rank.THIRD, 0); - put(Rank.SECOND, 0); - put(Rank.FIRST, 0); - }}; - - for (Lotto lotto : ticketList) { - int ticketResult = checkTicket(lotto.getTicket(), winningNumbers); - boolean isWinningBonusNumber = checkBonusNumber(lotto.getTicket(), bonusNumber); - - if (isWinning(ticketResult)) { - Rank rank = Rank.checkRank(ticketResult, isWinningBonusNumber); - result.put(rank, result.get(rank) + 1); - } - } - - return result; - } - - public double calculateEarningRate(int purchaseAmount, Map result) { - return (double)calculateWinningAmount(result) / purchaseAmount * 100 - 100; - } - - private boolean isWinning(int ticketResult) { - return ticketResult >= 3; - } - - private int checkTicket(List ticket, List winningNumbers) { - return (int)winningNumbers.stream() - .filter(ticket::contains) - .count(); - } - - private boolean checkBonusNumber(List ticket, int bonusNumber) { - return ticket.contains(bonusNumber); - } - - private int calculateWinningAmount(Map result) { - int winningAmount = 0; - for (Rank rank : result.keySet()) { - winningAmount += result.get(rank) * rank.getWinningAmount(); - } - return winningAmount; - } - - private int calculateAmount(int purchaseAmount) { - return purchaseAmount / TICKET_PRICE; - } - -} diff --git a/src/main/java/com/lotto/model/LottoTickets.java b/src/main/java/com/lotto/model/LottoTickets.java index f066a117..d713738a 100644 --- a/src/main/java/com/lotto/model/LottoTickets.java +++ b/src/main/java/com/lotto/model/LottoTickets.java @@ -6,41 +6,55 @@ import java.util.stream.Collectors; public class LottoTickets { - private static final List NUMBERS = initLottoNumbers(); - + private static final List numbers; private final List tickets; + static { + numbers = new ArrayList<>(); + for (int i = 1; i < 46; i++) { + numbers.add(i); + } + } + + public LottoTickets(int ticketCount) { + this.tickets = new ArrayList<>(); + addAutoTickets(ticketCount); + } - private LottoTickets(List tickets) { - this.tickets = tickets; + public LottoTickets(int ticketCount, List> manualTickets) { + this.tickets = new ArrayList<>(); + setManualTickets(manualTickets); + addAutoTickets(ticketCount- manualTickets.size()); } public List getTickets() { return Collections.unmodifiableList(tickets); } - public static LottoTickets createLottoTickets(int ticketCount) { - List tickets = new ArrayList<>(); - for(int i=0; i createTicket() { - Collections.shuffle(NUMBERS); - return NUMBERS.stream().limit(6).collect(Collectors.toList()); + private void setManualTickets(List> manualTickets) { + for (List manualTicket : manualTickets) { + tickets.add(createManualTicket(manualTicket)); + } } - private static List initLottoNumbers() { - List list = new ArrayList<>(); - for(int i = 1; i<46; i++){ - list.add(i); - } - return list; + private Lotto createManualTicket(List ticket) { + return new Lotto(ticket); + } + + private List createRandomNumbers() { + Collections.shuffle(numbers); + return numbers.stream().limit(6).collect(Collectors.toList()); } + + } diff --git a/src/main/java/com/lotto/model/Rank.java b/src/main/java/com/lotto/model/Rank.java index 4f08a1f8..4c44e709 100644 --- a/src/main/java/com/lotto/model/Rank.java +++ b/src/main/java/com/lotto/model/Rank.java @@ -1,11 +1,14 @@ package com.lotto.model; +import java.util.Arrays; +import java.util.stream.Collectors; + public enum Rank { - FIRST(6, 2_000_000_000), - SECOND(5, 30_000_000), - THIRD(5, 15_000_000), + FIFTH(3, 5_000), FOURTH(4, 50_000), - FIFTH(3, 5_000); + THIRD(5, 15_000_000), + SECOND(5, 30_000_000), + FIRST(6, 2_000_000_000); private int count; private int winningAmount; @@ -24,14 +27,15 @@ public int getWinningAmount() { } public static Rank checkRank(int count, boolean bonus) { - - for (Rank rank : Rank.values()) { - if (count == SECOND.count) { - return bonus ? SECOND : THIRD; - } - if (count == rank.count) - return rank; + if (count == SECOND.count) { + return bonus ? SECOND : THIRD; } - return null; + return getRankByCount(count); + } + + private static Rank getRankByCount(int count) { + return Arrays.stream(Rank.values()) + .filter(rank -> rank.count == count) + .collect(Collectors.toList()).get(0); } } diff --git a/src/main/java/com/lotto/model/WinningLotto.java b/src/main/java/com/lotto/model/WinningLotto.java new file mode 100644 index 00000000..b4bc2b9f --- /dev/null +++ b/src/main/java/com/lotto/model/WinningLotto.java @@ -0,0 +1,32 @@ +package com.lotto.model; + +import java.util.List; + +public class WinningLotto { + private final int bonusNumber; + private final Lotto numbers; + + public WinningLotto(List ticket, int bonusNumber) { + this.numbers = new Lotto(ticket); + this.bonusNumber = bonusNumber; + } + + public boolean compareBonusNumber(List ticket) { + return ticket.stream().anyMatch(s -> bonusNumber == s); + } + + public int compareTicket(List ticket) { + int matchedCount = 0; + for (int number : ticket) { + matchedCount += containNumber(number); + } + return matchedCount; + } + + private int containNumber(int number) { + if (this.numbers.getTicket().contains(number)) { + return 1; + } + return 0; + } +} diff --git a/src/main/java/com/lotto/util/ValidationUtil.java b/src/main/java/com/lotto/util/ValidationUtil.java new file mode 100644 index 00000000..82e9c801 --- /dev/null +++ b/src/main/java/com/lotto/util/ValidationUtil.java @@ -0,0 +1,43 @@ +package com.lotto.util; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +public class ValidationUtil { + private static final String NUMBER_PATTERN = "([1-9]|1[0-9]|2[0-9]|3[0-9]|4[0-5])((, )([1-9]|1[0-9]|2[0-9]|3[0-9]|4[0-5])){5}"; + + public static void validateManualCountRange(int count, int purchaseAmount) { + if (count > purchaseAmount / 1000 || count < 0) { + throw new IllegalArgumentException("숫자를 확인해주세요."); + } + } + + public static String[] validateTicketFormat(String ticketNumbers) { + + if (!Pattern.matches(NUMBER_PATTERN, ticketNumbers)) { + throw new IllegalArgumentException("형식이 올바르지 않습니다"); + } + return ticketNumbers.replaceAll(" ", "").split(","); + } + + public static void checkDuplicate(String[] ticketNumbers) { + Set result = new HashSet<>(); + for (String ticketNumber : ticketNumbers) { + result.add(ticketNumber); + } + if (result.size() != 6) { + throw new IllegalArgumentException("숫자가 중복되지 없도록 입력해주세요."); + } + } + + public static void validateBonusNumber(int bonusNumber, List winningNumbers) { + if (bonusNumber > 46 || bonusNumber < 1) { + throw new IllegalArgumentException("1 ~ 45 사이의 숫자를 입력해주세요."); + } + if (winningNumbers.contains(bonusNumber)) { + throw new IllegalArgumentException("당첨번호와 중복되지 않는 번호로 입력해주세요."); + } + } +} diff --git a/src/main/java/com/lotto/view/InputView.java b/src/main/java/com/lotto/view/InputView.java index 93485859..22603363 100644 --- a/src/main/java/com/lotto/view/InputView.java +++ b/src/main/java/com/lotto/view/InputView.java @@ -1,30 +1,93 @@ package com.lotto.view; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; +import com.lotto.util.ValidationUtil; + public class InputView { private static final String REQUEST_AMOUNT_MESSAGE = "구입 금액을 입력해 주세요."; private static final String REQUEST_WINNING_NUMBERS_MESSAGE = "당첨 번호를 입력해 주세요."; private static final String REQUEST_BONUS_NUMBER_MESSAGE = "보너스 번호를 입력해 주세요."; + private static final String REQUEST_MANUAL_NUMBER_COUNT_MESSAGE = "수동으로 구매할 로또 수를 입력해 주세요."; + private static final String REQUEST_MANUAL_NUMBERS_MESSAGE = "수동으로 구매할 번호를 입력해 주세요."; - private static final Scanner scanner = new Scanner(System.in); + private Scanner scanner; - public int getPurchaseAmount() { + public int inputPurchaseAmount() { System.out.println(REQUEST_AMOUNT_MESSAGE); - return Integer.parseInt(scanner.nextLine()); + return inputNumber(); + } + + public int inputManualCount() { + System.out.println(REQUEST_MANUAL_NUMBER_COUNT_MESSAGE); + return inputNumber(); } - public List getWinningNumbers() { + public List inputWinningNumbers() { System.out.println(REQUEST_WINNING_NUMBERS_MESSAGE); - String[] winningNumbers = scanner.nextLine().replaceAll(" ", "").split(","); - return Arrays.stream(winningNumbers).map(Integer::parseInt).collect(Collectors.toList()); + return inputTicketNumbers(); + } + + public List> inputManualNumbers(int count) { + System.out.println(REQUEST_MANUAL_NUMBERS_MESSAGE); + List> manualNumbers = new ArrayList<>(); + for (int i = 0; i < count; i++) { + manualNumbers.add(inputTicketNumbers()); + } + return manualNumbers; } - public int inputBonusNumber() { + public int inputBonusNumber(List winningNumbers) { System.out.println(REQUEST_BONUS_NUMBER_MESSAGE); - return scanner.nextInt(); + + int bonusNumber; + try { + bonusNumber = scanner.nextInt(); + ValidationUtil.validateBonusNumber(bonusNumber, winningNumbers); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + bonusNumber = inputBonusNumber(winningNumbers); + } + return bonusNumber; + } + + public void initScanner() { + this.scanner = new Scanner(System.in); } + + public void closeScanner() { + this.scanner.close(); + } + + private int inputNumber() { + int result; + try { + result = Integer.parseInt(scanner.nextLine()); + } catch (NumberFormatException e) { + System.out.println("숫자를 입력해주세요."); + result = inputPurchaseAmount(); + } + return result; + } + + private List inputTicketNumbers() { + String[] numbers; + while (true) { + try { + String input = scanner.nextLine(); + numbers = ValidationUtil.validateTicketFormat(input); + ValidationUtil.checkDuplicate(numbers); + break; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + continue; + } + } + return Arrays.stream(numbers).map(Integer::parseInt).collect(Collectors.toList()); + } + } diff --git a/src/main/java/com/lotto/view/OutputView.java b/src/main/java/com/lotto/view/OutputView.java index 59a6fcbb..a9b2d036 100644 --- a/src/main/java/com/lotto/view/OutputView.java +++ b/src/main/java/com/lotto/view/OutputView.java @@ -3,9 +3,10 @@ import java.util.List; import java.util.Map; -import model.Lotto; -import model.LottoTickets; -import model.Rank; +import com.lotto.model.Lotto; +import com.lotto.model.LottoResult; +import com.lotto.model.LottoTickets; +import com.lotto.model.Rank; public class OutputView { private static final String TICKET_AMOUNT_MESSAGE = "%d개를 구매했습니다.%n"; @@ -20,10 +21,12 @@ public void printTickets(LottoTickets tickets) { } } - public void printResult(Map result, double earningRate) { + public void printResult(LottoResult result, double earningRate) { + Map lottoResult = result.getResult(); + System.out.println(WINNING_RESULT_MESSAGE); - for (Rank rank : result.keySet()) { - System.out.printf("%d개 일치 (%d원)- %d개%n", rank.getCount(), rank.getWinningAmount(), result.get(rank)); + for (Rank rank : lottoResult.keySet()) { + System.out.printf("%d개 일치 (%d원)- %d개%n", rank.getCount(), rank.getWinningAmount(), lottoResult.get(rank)); } System.out.printf("총 수익률은 %s%%입니다", String.format("%.2f",earningRate)); }