Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[로또] 강건 미션 제출합니다. #1129

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,24 @@
# java-lotto-precourse


# 미션 - 로또

## 기능 구현

1. 1 ~ 45 까지 중복되지 않는 정수 6개 반환 기능
2. Lotto 클래스 getter, toString 구현
3. 당첨 번호 입력 기능
4. 보너스 번호 입력 기능
5. 등수 확인 기능
* 일반 등수만 확인 기능(1, 3, 4, 5등)
* 보너스 번호 포함 확인 기능(3등 중에서 2등 뽑기)
6. 로또 구입 금액 입력 기능
7. 총 구매 로또 개수 계산 기능
8. 로또 발행 기능
9. 등수별 당첨금액 및 번호 일치 개수 열거형
10. 당첨 내역 출력 기능
11. 수익률 출력 기능
12. 예외 처리
* IllegalArgumentException
* IllegalStateException
13. 메인 메서드 구현
182 changes: 181 additions & 1 deletion src/main/java/lotto/Application.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,187 @@
package lotto;
import camp.nextstep.edu.missionutils.Randoms;
import camp.nextstep.edu.missionutils.Console;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Application {
private static final int PRICEPERLOTTO = 1000;

public static void main(String[] args) {
// TODO: 프로그램 구현
int payMoney = getPayMoney();
int lottoPurchasesNum = calculateLottoPurchasesNum(payMoney);
List<Lotto> myLottoNum = myLottoNum(lottoPurchasesNum);
List<Integer> luckyNum = getLuckyNum();
int bonusNumber = getBonusNumber(luckyNum);
int[][] result = matchByLotto(luckyNum, myLottoNum, lottoPurchasesNum, bonusNumber);
displayResults(result,payMoney);

}

public static List<Integer> lottoNumberGenerator() {
List<Integer> lottoNumber = Randoms.pickUniqueNumbersInRange(1, 45, 6);
return lottoNumber;
}

public static int getPayMoney() {
while (true) {
try {
System.out.println("구입금액을 입력해 주세요.");
String unCheckedPayMoney = Console.readLine();
int payMoney = checkPayMoney(unCheckedPayMoney);
return payMoney;
} catch (NumberFormatException e) {
System.out.println("[ERROR] 구입 금액은 정수만 입력가능합니다.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}

public static int checkPayMoney(String unCheckedPayMoney) {
int checkPayMoney = Integer.parseInt(unCheckedPayMoney);
if (checkPayMoney < PRICEPERLOTTO || checkPayMoney % PRICEPERLOTTO > 0) {
throw new IllegalArgumentException("[ERROR] 구매금액은 1000으로 나누어 떨어져야합니다.");
}
return checkPayMoney;
}

public static int calculateLottoPurchasesNum(int payMoney) {
int lottoPurchasesNum = payMoney / PRICEPERLOTTO;
System.out.println(lottoPurchasesNum + "개를 구매했습니다.");
return lottoPurchasesNum;
}

public static List<Lotto> myLottoNum(int lottoPurchasesNum) {
List<Lotto> myLottoNum = new ArrayList<>();
for (int i = 1; i < lottoPurchasesNum + 1; i++) {
Lotto lotto = new Lotto(lottoNumberGenerator());
myLottoNum.add(lotto);
System.out.println(lotto);
}
return myLottoNum;
}

public static List<Integer> getLuckyNum() {
while (true) {
try {
System.out.println("\n당첨 번호를 입력해 주세요.");
String unCheckedLuckyNumber = Console.readLine();
List<Integer> luckyNum = checkLuckyNum(unCheckedLuckyNumber);
new Lotto(luckyNum);
return luckyNum;
} catch (NumberFormatException e) {
System.out.println("[ERROR] 로또 번호는 정수만 입력가능합니다.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}

public static List<Integer> checkLuckyNum(String unCheckedLuckyNumber) {
StringTokenizer tokenizer = new StringTokenizer(unCheckedLuckyNumber, ",");
List<Integer> checkLuckyNum = new ArrayList<>();
while (tokenizer.hasMoreTokens()) {
int token = Integer.parseInt(tokenizer.nextToken());
checkLuckyNum.add(token);
}
return checkLuckyNum;
}

public static int getBonusNumber(List<Integer> luckyNum) {
while (true) {
try {
System.out.println("\n보너스 번호를 입력해 주세요.");
String unCheckedBonusNumber = Console.readLine();
int bonusNumber = checkBonusNumber(unCheckedBonusNumber,luckyNum);
return bonusNumber;
} catch (NumberFormatException e) {
System.out.println("[ERROR] 보너스 번호는 정수만 입력가능합니다.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}

public static int checkBonusNumber(String unCheckedBonusNumber,List<Integer> luckyNum) {
int checkBonusNumber = Integer.parseInt(unCheckedBonusNumber);
if (checkBonusNumber < 0 || checkBonusNumber > 45) {
throw new IllegalArgumentException("[ERROR] 보너스 번호는 1부터 45 사이의 숫자여야 합니다.");
}
if (luckyNum.contains(checkBonusNumber)) {
throw new IllegalArgumentException("[ERROR] 보너스 번호는 당첨 번호와 중복될 수 없습니다.");
}
return checkBonusNumber;
}

public static int getMatchPoint(List<Integer> luckyNum, List<Integer> lottoNum) {
int matchPoint = 0;
for (int i = 0; i < luckyNum.size(); i++) {
if (lottoNum.contains(luckyNum.get(i))) {
matchPoint += 1;
}
}
return matchPoint;
}

public static int[][] matchByLotto(List<Integer> luckyNum, List<Lotto> myLottoNum, int purchaseNum, int bonusNum) {
int[][] matchPoints = new int[purchaseNum][2];
for (int i = 0; i < purchaseNum; i++) {
int matchPoint = getMatchPoint(luckyNum, myLottoNum.get(i).getNumbers());
matchPoints[i][0] = matchPoint;
if (matchPoint == 5) {
matchPoints[i][1] = calculateSecondtoThird(myLottoNum.get(i).getNumbers(), bonusNum);
}
}
return matchPoints;
}

public static int calculateSecondtoThird(List<Integer> myLottoNum, int bonusNumber) {
for (int i = 0; i < myLottoNum.size(); i++) {
if (myLottoNum.contains(bonusNumber)) {
return 1;
}
}
return 0;
}

public static void displayResults(int[][] matchPoints, int payMoney) {
int[] rankCounts = new int[PrizeMoneyByRank.values().length];

for (int[] result : matchPoints) {
PrizeMoneyByRank rank = PrizeMoneyByRank.getRankByMatchCount(result[0], result[1]);
rankCounts[rank.ordinal()]++;
}

printStatistics(rankCounts);
double totalProfit = calculateTotalProfit(rankCounts);
displayProfitRate(payMoney, totalProfit);
}

public static void printStatistics(int[] rankCounts) {
System.out.println("\n당첨 통계\n---");
System.out.printf("3개 일치 (5,000원) - %d개%n", rankCounts[PrizeMoneyByRank.FIFTH.ordinal()]);
System.out.printf("4개 일치 (50,000원) - %d개%n", rankCounts[PrizeMoneyByRank.FOURTH.ordinal()]);
System.out.printf("5개 일치 (1,500,000원) - %d개%n", rankCounts[PrizeMoneyByRank.THIRD.ordinal()]);
System.out.printf("5개 일치, 보너스 볼 일치 (30,000,000원) - %d개%n", rankCounts[PrizeMoneyByRank.SECOND.ordinal()]);
System.out.printf("6개 일치 (2,000,000,000원) - %d개%n", rankCounts[PrizeMoneyByRank.FIRST.ordinal()]);
}

public static double calculateTotalProfit(int[] rankCounts) {
double totalProfit = 0;
for (PrizeMoneyByRank rank : PrizeMoneyByRank.values()) {
if (rank != PrizeMoneyByRank.TRASH) {
totalProfit += rank.getPrizeMoney() * rankCounts[rank.ordinal()];
}
}
return totalProfit;
}

public static void displayProfitRate(double payMoney, double totalProfit) {
double profitRate = totalProfit / payMoney * 100;
System.out.printf("총 수익률은 %.1f%%입니다.%n", profitRate);
}
}
}
25 changes: 23 additions & 2 deletions src/main/java/lotto/Lotto.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
package lotto;

import java.util.List;

public class Lotto {
Expand All @@ -11,10 +10,32 @@ public Lotto(List<Integer> numbers) {
}

private void validate(List<Integer> numbers) {
if (numbers.size() != 6) {
final int lottoSize = 6;
if (numbers.size() != lottoSize) {
throw new IllegalArgumentException("[ERROR] 로또 번호는 6개여야 합니다.");
}
for(int number : numbers) {
if (number < 0 || number > 45) {
throw new IllegalArgumentException("[ERROR] 로또 번호는 1부터 45 사이의 숫자여야 합니다.");
}
if (numbers.indexOf(number) != numbers.lastIndexOf(number)){
throw new IllegalArgumentException("[ERROR] 로또 번호에는 중복이 없어야 합니다.");
}

}
}
public List<Integer> getNumbers(){
return numbers;
}
@Override
public String toString(){
return numbers.toString();
}





// TODO: 추가 기능 구현

}
44 changes: 44 additions & 0 deletions src/main/java/lotto/PrizeMoneyByRank.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package lotto;

public enum PrizeMoneyByRank {
FIFTH(3,5000),
FOURTH(4,50000),
THIRD(5,1500000),
SECOND(5,30000000),
FIRST(6,2000000000),
TRASH(0,0);

private final int matchCount;
private final int prizeMoney;


PrizeMoneyByRank(int matchCount, int prizeMoney){
this.matchCount = matchCount;
this.prizeMoney = prizeMoney;
}
public int getMatchCount(){
return matchCount;
}

public int getPrizeMoney() {
return prizeMoney;
}
public static PrizeMoneyByRank getRankByMatchCount(int matchCount, int bonusMatch){
if(matchCount == FIRST.getMatchCount()){
return FIRST;
}
if(matchCount == SECOND.getMatchCount()&& bonusMatch == 1 ){
return SECOND;
}
if(matchCount == THIRD.getMatchCount()&& bonusMatch == 0 ){
return THIRD;
}
if(matchCount == FOURTH.getMatchCount()){
return FOURTH;
}
if(matchCount == FIFTH.getMatchCount()){
return FIFTH;
}
return TRASH;
}
}