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

[로또 미션] 신예린 미션 제출합니다. #19

Open
wants to merge 32 commits into
base: nyeroni
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
958541e
feat: 로또 구매할 금액 입력
nyeroni May 1, 2024
8627586
feat: 구매한 로또 출력
nyeroni May 1, 2024
c086150
feat: 로또 랜덤 번호로 생성
nyeroni May 1, 2024
d435b8e
feat: 로또 생성
nyeroni May 1, 2024
07b7bc7
feat: 총 구매한 로또를 list로 생성
nyeroni May 1, 2024
5ed6fea
feat: 구매할 가격 입력 후 해당 가격 만큼 로또 생성 및 출력
nyeroni May 1, 2024
2fd7c31
feat: 실행
nyeroni May 1, 2024
ebbd2b3
feat: 랜덤 숫자 생성 변경
nyeroni May 1, 2024
2a199f1
feat: 정렬 코드 삭제
nyeroni May 1, 2024
2d59e3d
feat: 로또 랜덤 생성 중복 방지 추가
nyeroni May 2, 2024
6b2269c
feat: 당첨 번호 입력 및 당첨 개수, 수익률 계산 및 출력
nyeroni May 2, 2024
7052bdd
feat: 메서드 명 변경 및 로또 생성 오류 해결
nyeroni May 3, 2024
4375301
Refactor: 불필요한 코드 정리
nyeroni May 4, 2024
e2860da
feat: 요구사항 정리
nyeroni May 6, 2024
49773c8
feat: 출력 문구 enum으로 설정
nyeroni May 6, 2024
9c28320
feat: 출력 문구 수정 및 로또 출력 방식 변경
nyeroni May 6, 2024
2fe5105
feat: 변수명 변경 및 보너스 번호 매치 메서드 생성
nyeroni May 6, 2024
4595b55
feat: 수동 로또 생성
nyeroni May 6, 2024
561a3b3
feat: 수동 로또 생성 및 로또 목록 출력 방식 변경
nyeroni May 6, 2024
0e387fb
feat: enum타입 수정
nyeroni May 6, 2024
cfe53f4
feat: 투입 금액 및 로또 구매 개수 예외 처리
nyeroni May 6, 2024
ef9bdab
feat: 수동 개수 예외 처리 및 설정
nyeroni May 6, 2024
3d69130
feat: 보너스넘버 예외 처리 및 설정
nyeroni May 6, 2024
f1804d5
feat: 로또 예외 처리
nyeroni May 6, 2024
652c085
feat: 예외 처리 및 수정
nyeroni May 6, 2024
7beec8d
feat: 결과 출력 수정
nyeroni May 6, 2024
48b8f00
feat: 예외 문구 수정
nyeroni May 6, 2024
04d0f96
feat: 예외 문구 수정
nyeroni May 6, 2024
2fd040c
feat: 생성자 추가
nyeroni May 6, 2024
4f9977c
feat: 생성자 추가
nyeroni May 6, 2024
2f51b48
test: 테스트코드 작성
nyeroni May 6, 2024
36e8947
test: 테스트코드 작성
nyeroni May 6, 2024
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
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
## 🔨 구현 기능 목록

### 입력

- 구입 금액 입력
- 한 장당 1000원
- 1000원으로 나누어 떨어지지 않으면 예외 처리
- 수동으로 구매할 로또 수 입력
- 숫자 외의 입력은 모두 예외처리
- 수동으로 구매할 로또 번호 입력
- 번호는 쉼표(,)로 구분
- 숫자와 쉼표(,) 외의 입력은 모두 예외 처리
- 6개가 되지 않는다면 예외 처리
- 당첨 번호 입력
- 번호는 쉼표(,)로 구분
- 숫자와 쉼표(,) 외의 입력은 모두 예외 처리
- 6개가 되지 않는다면 예외 처리
- 보너스 번호 입력
- 숫자 외의 입력은 모두 예외처리


### 출력


- 수동 로또와 자동 로또 발행
- 오름차순으로 정렬해서 보여줌
- 중복되지 않는 6개 숫자
- 당첨 내역 출력
- `3개 일치 (5000원) - n개`
- `4개 일치 (50000원) - n개`
- `5개 일치 (1500000원) - n개`
- `5개 일치, 보너스 볼 일치 (30000000원) - n개`
- `6개 일치 (2000000000원) - n개`
- 수익률 출력
- `총 수익률은 n입니다.`
- 소숫점 둘째자리 밑으론 버림
- 예외 상황시 에러 문구 출력
- `[ERROR] error message`

### 게임 진행

- 구입 금액을 입력
- 수동으로 구매할 로또 수 입력
- 수동 로또 번호 입력
- 로또 번호 1~45 사이의 중복되지 않는 정수로 6개 무작위 추첨해서 구입한 개수(수동 로또 개수 제외) 만큼 자동 로또 발행
- 당첨 번호와 보너스 번호를 입력받음
- 일치하는 내역과 총 수익률을 출력
- 예외가 발생할 경우 예외 문구 출력
11 changes: 11 additions & 0 deletions src/main/java/Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import controller.LottoController;

import java.io.IOException;

public class Application {

public static void main(String [] args) throws IOException {
LottoController lottoController = new LottoController();
lottoController.startLottoGame();
}
}
145 changes: 145 additions & 0 deletions src/main/java/controller/LottoController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package controller;

import model.*;
import view.InputView;
import view.OutputView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class LottoController {
private InputView inputView = new InputView();
private OutputView outputView = new OutputView();
private LottoList lottoList;

public LottoController() {
}
public void startLottoGame() {
UserCount userMoney = receiveMoneyInput();
ManualCount manualCount = manualLottoCount();
if(manualCount.getManualCount() == 0){
displayLottoTickets(userMoney, null);
}
else{
displayLottoTickets(userMoney, manualLottoNumbers(manualCount.getManualCount()));
}
Lotto winningNumbers = getWinningNumbers();
BonusNumber bonusNum = receiveBonusNumberInput();
validateDuplicate(winningNumbers, bonusNum);

List<Integer> matchCounts = calculateMatches(lottoList, winningNumbers, bonusNum);
double winRate = calculateWinningRate(matchCounts, userMoney);
outputView.printResults(matchCounts, Math.floor(winRate*100)/100 );
}
private ManualCount manualLottoCount(){
return new ManualCount(inputView.inputManualLottoCount());
}
private List<Lotto> manualLottoNumbers(int count){
List<String> manualLottoNums = inputView.manualLottos(count);
List<Lotto> manualLottos = new ArrayList<>();

for (String manualLotto : manualLottoNums) {
Lotto lotto = new Lotto();
manualLottos.add(lotto.convertToList(manualLotto));
}
return manualLottos;
}

private BonusNumber receiveBonusNumberInput() {
return new BonusNumber(inputView.inputBonusNumber());
}

private void validateDuplicate(Lotto winningLotto, BonusNumber bonusNumber){
winningLotto.validateDuplicateWithBonus(bonusNumber.getBonusNumber());
}

private UserCount receiveMoneyInput() {
return new UserCount(inputView.inputPrice());
}

private void displayLottoTickets(UserCount count, List<Lotto> lottos){
int autoCount = 0;
int manualCount = 0;
if(lottos == null){
autoCount = count.getCount();
manualCount = 0;
}
else{
autoCount = count.getCount() - lottos.size();
manualCount = lottos.size();
}
outputView.printTicketCount(autoCount, manualCount);
lottoList = generateLottoList(autoCount, lottos);
outputView.printLottoNumbers(lottoList);
}
LottoList generateLottoList(int count, List<Lotto> lottos){
lottoList = new LottoList();

if(lottos != null){
for (Lotto lotto : lottos) {
lottoList.setLottoList(lotto);
}
}
for(int i=0; i<count; i++){
lottoList.setLottoList(generateLotto());
}
return lottoList;
}
private Lotto generateLotto(){
List<Integer> numbers = new ArrayList<>();
AutoLotto autoLotto = new AutoLotto();
numbers = autoLotto.getAutoLotto();
return new Lotto(numbers);
}

private Lotto getWinningNumbers(){
String winnerNumbersStr = inputView.inputWinnerNumber();
Lotto winningLotto = new Lotto();
return winningLotto.convertToList(winnerNumbersStr);
}


private List<Integer> calculateMatches(LottoList ticketList, Lotto winningNumbers, BonusNumber bonusNum) {
List<Integer> matchCounts = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0));

for (Lotto ticket : ticketList.getLottoList()) {
int countMatches = ticket.calculateMatches(winningNumbers);
updateMatchCounts(matchCounts, countMatches, bonusNum);
}

return matchCounts;
}


private void updateMatchCounts(List<Integer> matchCounts, int countMatches, BonusNumber bonusNum) {
Predicate<Integer> isBonusMatch = num -> num == 5 && bonusNum.getBonusNumber() > 0;

if (countMatches == 3) {
matchCounts.set(0, matchCounts.get(0) + 1);
} else if (countMatches == 4) {
matchCounts.set(1, matchCounts.get(1) + 1);
} else if (countMatches == 5) {
if (isBonusMatch.test(countMatches)) {
matchCounts.set(3, matchCounts.get(3) + 1);
} else {
matchCounts.set(2, matchCounts.get(2) + 1);
}
} else if (countMatches == 6) {
matchCounts.set(4, matchCounts.get(4) + 1);
}

}
double calculateWinningRate(List<Integer> matchCounts, UserCount count) {
int totalWinnings = matchCounts.get(0) * 5000 +
matchCounts.get(1) * 50000 +
matchCounts.get(2) * 1500000 +
matchCounts.get(3) * 30000000 +
matchCounts.get(4) * 2000000000;

double winningRate = (double) totalWinnings / (double) count.getPrice();
return Math.floor(winningRate * 100) / 100;
}

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

import java.util.*;

public class AutoLotto {
private static final int MIN_LOTTO_NUMBER = 1;
private static final int MAX_LOTTO_NUMBER = 45;
private static final int CNT_LOTTO_NUMBER = 6;

private static List<Integer> lottoNums = new ArrayList<>();
public AutoLotto(){
createAutoLotto();
}
public void createAutoLotto(){

List<Integer> numbers = new ArrayList<>();
for (int i = MIN_LOTTO_NUMBER; i <= MAX_LOTTO_NUMBER; i++) {
numbers.add(i);
}
Collections.shuffle(numbers);
lottoNums = new ArrayList<>();
for (int i = 0; i < CNT_LOTTO_NUMBER; i++) {
int uniqueNumber = numbers.get(i);
while (lottoNums.contains(uniqueNumber)) {
Copy link

Choose a reason for hiding this comment

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

궁금한점이 있습니다. numbers에는 이미 유니크한 숫자들이 shuffle되어있는 것 아닌가요? 이미 중복되지 않는 것은 보장된 것 같은데 한번 더 중복을 체크하시는 이유가 궁금합니다.

Collections.shuffle(numbers);
uniqueNumber = numbers.get(i);
}
lottoNums.add(uniqueNumber);
}
Collections.sort(lottoNums);
}
public List<Integer> getAutoLotto(){
return lottoNums;
}

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

public class BonusNumber {

private int bonusNumber;

public BonusNumber(String bonusNumber){
this.bonusNumber = convertStringToInt(bonusNumber)
;
}

public int convertStringToInt(String bonusNumber){
try {
return Integer.parseInt(bonusNumber);
} catch (NumberFormatException e) {
System.err.println("[ERROR] 숫자로만 입력해주세요.");
throw e;
}
}
public int getBonusNumber(){
return bonusNumber;
}
}
78 changes: 78 additions & 0 deletions src/main/java/model/Lotto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package model;

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

public class Lotto {
private static final int BONUS_NUMBER_INDEX = 6;
private List<Integer> numbers;

public Lotto(List<Integer> numbers) {
this.numbers = numbers;
}
public Lotto(){
}
public Lotto convertToList(String lottoNumbersStr) {
String[] str = lottoNumbersStr.split(",\\s*");
List<Integer> lottoList = new ArrayList<>();
for (String s : str) {
lottoList.add(convertStringToInt(s));
}

Lotto lotto = new Lotto(lottoList);
validate(lotto.getNumbers());
return lotto;
}
private int convertStringToInt(String price){
try {
return Integer.parseInt(price);
} catch (NumberFormatException e) {
System.err.println("[ERROR] 숫자로만 입력해주세요.");
throw e;
}
}
private void validate(List<Integer> numbers){
validateSize(numbers);
validateRange(numbers);
validateDuplicate(numbers);
}
void validateSize(List<Integer> numbers){
if(numbers.size() != 6){
throw new IllegalArgumentException("[ERROR] 로또 번호는 6개 입력해야 합니다.");
}
}
void validateRange(List<Integer> numbers){
for(int num : numbers){
if(num<=0||num>45){
throw new IllegalArgumentException("[ERROR] 로또 번호는 1부터 45 사이의 숫자로 입력해야 합니다.");
}
}
}
void validateDuplicate(List<Integer> numbers){
List<Integer> tmp = numbers;
if(tmp.stream().distinct().count()!=numbers.size()){
throw new IllegalArgumentException("[ERROR] 로또 번호에 중복된 숫자가 있습니다.");
}

}
public List<Integer>getNumbers(){
return numbers;
}

public int calculateMatches(Lotto winningLotto) {
int cnt = 0;
List<Integer> winningLottoList = winningLotto.getNumbers();
for (Integer integer : winningLottoList) {
if(numbers.contains(integer)){
cnt ++;
}
}
return cnt;
}

public void validateDuplicateWithBonus(int bonusNumber) {
if (numbers.contains(bonusNumber)) {
throw new IllegalArgumentException("[ERROR] 보너스 번호는 당첨 번호와 중복되어서는 안 됩니다.");
}
}
}
18 changes: 18 additions & 0 deletions src/main/java/model/LottoList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package model;

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

public class LottoList {
List<Lotto> lottoList = new ArrayList<>();
private int totalPrice;
public LottoList(){

}
public void setLottoList(Lotto lotto){
lottoList.add(lotto);
}
public List<Lotto> getLottoList(){
return lottoList;
}
}
25 changes: 25 additions & 0 deletions src/main/java/model/ManualCount.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package model;

public class ManualCount {
private int manualCount;

public ManualCount(){

}
public ManualCount(String manualCount){
this.manualCount = convertStringToInt(manualCount)
;
}

public int convertStringToInt(String manualCount){
try {
return Integer.parseInt(manualCount);
} catch (NumberFormatException e) {
System.err.println("[ERROR] 숫자로만 입력해주세요.");
throw e;
}
}
public int getManualCount(){
return manualCount;
}
}
Loading