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

[로또 게임] 박지현 2차 과제 제출합니다. #15

Open
wants to merge 2 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
5 changes: 4 additions & 1 deletion src/main/java/lotto/Application.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package lotto;

import camp.nextstep.edu.missionutils.Console;

public class Application {
public static void main(String[] args) {
// TODO: 프로그램 구현
RunApplication runApplication = new RunApplication();
runApplication.run();
}
}
30 changes: 30 additions & 0 deletions src/main/java/lotto/Exception.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package lotto;

public class Exception {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이왕 Exception 클래스 만든거 Java의 RuntimeException 같은거 상속한번 받아보지 아쉽네요

void exceptionOfLength(String[] numbers){
if(numbers.length != 6) {
throw new IllegalArgumentException("[ERROR] 로또 번호는 6개여야 합니다.");
}
}

void exceptionOfNumber(String[] numbers) {
for (String n : numbers) {
int number = Integer.parseInt(n);
if (number < 1 || number > 45) {
throw new IllegalArgumentException("[ERROR] 로또 번호는 1부터 45 사이의 숫자여야 합니다.");
}
}
}

void exceptionOfBonus(int bonusNumber){
if(bonusNumber < 1 || bonusNumber > 45) {
throw new IllegalArgumentException("[ERROR] 로또 번호는 1부터 45 사이의 숫자여야 합니다.");
}
}

void ExceptionOfPrice(int lottoPrice) {
if (lottoPrice % 1000 != 0) {
throw new IllegalArgumentException("[ERROR] 구입 금액은 1,000원 단위여야 합니다.");
}
}
}
59 changes: 59 additions & 0 deletions src/main/java/lotto/Insert.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package lotto;

import camp.nextstep.edu.missionutils.Console;

public class Insert {
String[] numbers = new String[6];
int bonusNumber;

//구입 금액 입력
void insertPrice(int lottoPrice) {
Exception exceptionOfPrice = new Exception();
exceptionOfPrice.ExceptionOfPrice(lottoPrice);
System.out.println(lottoPrice / 1000 + "개를 구매했습니다.");
}

String[] insertNumber() {
while(true) {
try {
System.out.println("당첨 번호를 입력해 주세요.");
String luckyNumber = Console.readLine();
numbers = luckyNumber.split(",");

//1-45 사이 숫자 아닌 경우 예외처리
Exception exceptionOfNumber = new Exception();
exceptionOfNumber.exceptionOfNumber(numbers);
//6개가 아닌 경우 예외처리
Exception exceptionOfLength = new Exception();
exceptionOfLength.exceptionOfLength(numbers);

break;
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
return numbers;
}

void insertBonus() {
while (true) {
try {
System.out.println("보너스 번호를 입력해 주세요.");
String bonus = Console.readLine();
bonusNumber = Integer.parseInt(bonus);

Exception exceptionOfBonus = new Exception();
exceptionOfBonus.exceptionOfBonus(bonusNumber);

break;

} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}

int getBonusNumber(){
return bonusNumber;
}
}
16 changes: 7 additions & 9 deletions src/main/java/lotto/Lotto.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,16 @@
import java.util.List;

public class Lotto {
private final List<Integer> numbers;
private final List<Integer> lottoNumbers;

public Lotto(List<Integer> numbers) {
validate(numbers);
this.numbers = numbers;
public Lotto(List<Integer> lottoNumbers) {
validate(lottoNumbers);
this.lottoNumbers = lottoNumbers;
}

private void validate(List<Integer> numbers) {
if (numbers.size() != 6) {
private void validate(List<Integer> lottoNumbers) {
if (lottoNumbers.size() != 6) {
throw new IllegalArgumentException();
}
}

// TODO: 추가 기능 구현
}
}
20 changes: 20 additions & 0 deletions src/main/java/lotto/Print.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package lotto;

public class Print {
void printStatistics(int[] winningCount) {
for (WinningEnum winning : WinningEnum.values()) {
System.out.println(winning.getMessage() + winningCount[winning.getCount()] + "개");
}
}

//수익률 출력
void printEarningRate(int[] winningCount, int lottoPrice) {
int totalPrice = 0;
for (WinningEnum winning : WinningEnum.values()) {
totalPrice += (winning.getPrice() * winningCount[winning.getCount()]);
}
double e = (double) totalPrice / lottoPrice;
double earningRate = (Math.round(e*1000)/10.0);
System.out.println("총 수익률은 " + earningRate + "%입니다.");
}
}
45 changes: 45 additions & 0 deletions src/main/java/lotto/RandomLotto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package lotto;

import camp.nextstep.edu.missionutils.Randoms;

import java.util.*;

public class RandomLotto {
List<List<Integer>> allLottoNumbers = new ArrayList<>(); //로또 리스트들을 저장하는 리스트
String[] numbers = new String[6];
int[] winningCount = new int[8];
Insert insert = new Insert();

void setBonus() {
insert.insertBonus();
}

// 구입 금액만큼 로또 번호를 랜덤으로 출력
void randomLotto(int lottoPrice) {
for (int i = 0; i < lottoPrice / 1000; i++) {
List<Integer> lottoNumbers = Randoms.pickUniqueNumbersInRange(1, 45, 6);
Lotto lotto = new Lotto(lottoNumbers); //list 가 유효한지 검증
Collections.sort(lottoNumbers); //오름차순 정렬
allLottoNumbers.add(lottoNumbers);
System.out.println(lottoNumbers);
}
}

void insertNumber() {
numbers = insert.insertNumber();
}

//당첨 통계 계산
void produceStatistics() {
int bonusNumber = insert.getBonusNumber();
StatisticsCalculator statisticsCalculator = new StatisticsCalculator();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

의존성이 있는 객체가 있다면 새로 생성할게 아니라 필드에 명시해두고 가져다 쓰는게 일반적입니다. 함수에서 생성하면 너무많이 생성될 수 도 있을것 같아요

statisticsCalculator.produceStatistics(allLottoNumbers, numbers, winningCount, bonusNumber);
}

//당첨 내역과 수익률
void printAll(int lottoPrice) {
Print print = new Print();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

마찬가지로 의존성관리를 좀더 공부해보세요

print.printStatistics(winningCount);
print.printEarningRate(winningCount, lottoPrice);
}
}
36 changes: 36 additions & 0 deletions src/main/java/lotto/RunApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package lotto;

import camp.nextstep.edu.missionutils.Console;
public class RunApplication {
void run() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

굉장히 맘에드는 함수입니다. 가독성이 훌륭합니다. 다만 클래스명이 좀 아쉽네요. 함수명이 단순히 run()이라면 클래스명이라도 좀더 직관적이었으면 좋겠어요.

while(true) {
try {
System.out.println("구입금액을 입력해 주세요.");
String price = Console.readLine();
int lottoPrice = Integer.parseInt(price);

//로또 구입 금액 입력
Insert insert = new Insert();
insert.insertPrice(lottoPrice);

//구입 금액만큼 랜덤 로또 번호 출력
RandomLotto randomLotto = new RandomLotto();
randomLotto.randomLotto(lottoPrice);

//당첨 번호, 보너스 번호 입력
randomLotto.insertNumber();
randomLotto.setBonus();

//당첨 통계
randomLotto.produceStatistics();
//당첨 내역과 수익률 출력
randomLotto.printAll(lottoPrice);

break;

} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
}
25 changes: 25 additions & 0 deletions src/main/java/lotto/StatisticsCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package lotto;

import java.util.List;

public class StatisticsCalculator {
void produceStatistics(List<List<Integer>> allLottoNumbers, String[] numbers, int[] winningCount, int bonusNumber) {
//int bonusNumber = insert.getBonusNumber();
System.out.println("당첨 통계");
System.out.println("---");

for (List<Integer> lottoNumbers : allLottoNumbers) {
int count = 0;
for (String n : numbers) {
if (lottoNumbers.contains(Integer.parseInt(n))) {
count++;
}
}
if (count == 5 && lottoNumbers.contains(bonusNumber)) {
winningCount[7]++;
return;
}
winningCount[count]++;
}
}
}
31 changes: 31 additions & 0 deletions src/main/java/lotto/WinningEnum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package lotto;

public enum WinningEnum {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

enum을 잘활용했네요. 다만 enum 객체는 상수처럼 활용하려면 대문자로 사용하는 것이 일반적입니다. ex. THREE(),FOUR()..

three(3, 5000, "3개 일치 (5,000원) - "),
four(4, 50000, "4개 일치 (50,000원) - "),
five(5, 1500000, "5개 일치 (1,500,000원) - "),
bonus(7, 30000000, "5개 일치, 보너스 볼 일치 (30,000,000원) - "),
six(6, 2000000000, "6개 일치 (2,000,000,000원) - ");

private final int count;
private final int price;
private final String message;

WinningEnum(int count, int price, String message) {
this.count = count;
this.price = price;
this.message = message;
}

public int getCount() {
return count;
}

public int getPrice() {
return price;
}

public String getMessage() {
return message;
}
}