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주차]객체지향 코드 연습(yunjin1213) #29

Open
wants to merge 11 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
7 changes: 0 additions & 7 deletions src/main/java/lotto/Application.java

This file was deleted.

20 changes: 0 additions & 20 deletions src/main/java/lotto/Lotto.java

This file was deleted.

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

public enum ErrorMessage {
ERROR_INVALID_AMOUNT("[ERROR] 구입 금액은 1,000원 단위로 입력해야 합니다."),
ERROR_INVALID_NUMBER("[ERROR] 로또 번호는 1부터 45 사이의 숫자여야 합니다."),
ERROR_DUPLICATE_NUMBER("[ERROR] 중복된 번호가 존재합니다."),
ERROR_NUMBER_COUNT("[ERROR] 로또 번호는 정확히 6개를 입력해야 합니다.");
private final String message;

// 생성자
ErrorMessage(String message) {
this.message = message;
}

// 메시지 반환 메서드
public String getMessage() {
return message;
}
}
29 changes: 29 additions & 0 deletions src/main/java/lotto/constant/PromptMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package lotto.constant;

public enum PromptMessage {
PROMPT_PURCHASE_AMOUNT("구입 금액을 입력해 주세요: "),
PROMPT_WINNING_NUMBERS("당첨 번호를 입력해 주세요. (1~45 숫자 6개를 쉼표로 구분해서 입력)"),
PROMPT_BONUS_NUMBER("보너스 번호를 입력해 주세요. (1~45 사이 숫자)"),
WINNING_STATISTICS("당첨 통계");

private final String message;

// 생성자를 통해 메시지를 설정
PromptMessage(String message) {
this.message = message;
}

// 동적 값이 필요한 경우에는 별도의 메서드로 처리
public static String purchasedTickets(int count) {
return String.format("%d개를 구매했습니다.", count);
}

public static String countCorrect(int correctCount, int prize, int matchCount) {
return String.format("%d개 일치 (%d원) - %d개", correctCount, prize, matchCount);
}

// 메시지를 반환하는 메서드
public String getMessage() {
return message;
}
}
34 changes: 34 additions & 0 deletions src/main/java/lotto/constant/Rank.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package lotto.constant;

public class Rank {
public enum RankEnum {
FIRST(6, false, 2_000_000_000),
SECOND(5, true, 30_000_000),
THIRD(5, false, 1_500_000),
FOURTH(4, false, 50_000),
FIFTH(3, false, 5_000),
NONE(0, false, 0);

private final int matchCount;
private final boolean matchBonus;
private final int prize;

RankEnum(int matchCount, boolean matchBonus, int prize) {
this.matchCount = matchCount;
this.matchBonus = matchBonus;
this.prize = prize;
}

public int getMatchCount() {
return matchCount;
}

public int getPrize() {
return prize;
}

public boolean isMatchBonus() {
return matchBonus;
}
}
}
19 changes: 19 additions & 0 deletions src/main/java/lotto/machine/KioskStarter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package lotto.machine;

import lotto.repository.Memory;
import lotto.view.LottoKiosk;

public class KioskStarter {
public static void main(String[] args) {
LottoSeller lottoSeller = new LottoSeller();
LottoNumberGenerator lottoNumberGenerator = new LottoNumberGenerator(); // LottoNumberGenerator 생성
Memory memory = new Memory();
WinningSystem winningSystem = new WinningSystem(memory);

// LottoKiosk에 모든 인자 전달
LottoKiosk kiosk = new LottoKiosk(lottoSeller, lottoNumberGenerator, winningSystem, memory);

// 시작
kiosk.start();
}
}
60 changes: 60 additions & 0 deletions src/main/java/lotto/machine/Lotto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package lotto.machine;

import lotto.constant.ErrorMessage;

import java.util.List;

public class Lotto {

private static final int LOTTO_NUMBER_SIZE = 6;
private static final int MIN_LOTTO_NUMBER = 1;
private static final int MAX_LOTTO_NUMBER = 45;

private final List<Integer> numbers;

public Lotto(List<Integer> numbers) {
// 유효성 검사를 생성자 내부에서 처리
validateNumbers(numbers);
this.numbers = numbers;
}

// 보너스 번호 유효성 검사
public static void validateBonusNumber(int bonusNumber) {
if (bonusNumber < MIN_LOTTO_NUMBER || bonusNumber > MAX_LOTTO_NUMBER) {
throw new IllegalArgumentException(ErrorMessage.ERROR_INVALID_NUMBER.getMessage());
}
}

// 로또 번호 유효성 검사
private void validateNumbers(List<Integer> numbers) {
validateSize(numbers);
validateRange(numbers);
validateDuplicates(numbers);
}

// 로또 번호 개수 유효성 검사
private void validateSize(List<Integer> numbers) {
if (numbers.size() != LOTTO_NUMBER_SIZE) {
throw new IllegalArgumentException(ErrorMessage.ERROR_NUMBER_COUNT.getMessage());
}
}

// 숫자 범위 유효성 검사
private void validateRange(List<Integer> numbers) {
if (numbers.stream().anyMatch(number -> number < MIN_LOTTO_NUMBER || number > MAX_LOTTO_NUMBER)) {
throw new IllegalArgumentException(ErrorMessage.ERROR_INVALID_NUMBER.getMessage());
}
}

// 중복 유효성 검사
private void validateDuplicates(List<Integer> numbers) {
if (numbers.stream().distinct().count() != LOTTO_NUMBER_SIZE) {
throw new IllegalArgumentException(ErrorMessage.ERROR_DUPLICATE_NUMBER.getMessage());
}
}

// 로또 번호 반환
public List<Integer> getNumbers() {
return numbers;
}
}
22 changes: 22 additions & 0 deletions src/main/java/lotto/machine/LottoNumberGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package lotto.machine;

import camp.nextstep.edu.missionutils.Randoms;
import lotto.repository.Memory;

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class LottoNumberGenerator {

public void generateNumbers(Memory memory) {
int ticketCount = memory.getTicketCount();

// Stream을 사용해 티켓 개수만큼 로또 번호 생성 후 Memory에 저장
IntStream.range(0, ticketCount)
.mapToObj(i -> Randoms.pickUniqueNumbersInRange(1, 45, 6)
.stream()
.sorted() // 오름차순 정렬
.collect(Collectors.toList()))
.forEach(memory::saveGeneratedNumbers); // 생성된 번호를 Memory에 저장
}
}
29 changes: 29 additions & 0 deletions src/main/java/lotto/machine/LottoParser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package lotto.machine;

import lotto.constant.ErrorMessage;

import java.util.List;
import java.util.stream.Collectors;

public class LottoParser {

private static final String NUMBER_SEPARATOR = ",";

public static List<Integer> parseWinningNumbers(String input) {
String[] split = input.split(NUMBER_SEPARATOR);

List<Integer> numbers;
try {
numbers = List.of(split).stream()
.map(String::trim) // 공백 제거
.map(Integer::parseInt) // 문자열을 정수로 변환
.collect(Collectors.toList());
} catch (NumberFormatException e) {
// Error enum을 사용해 예외 메시지 출력
throw new IllegalArgumentException(ErrorMessage.ERROR_INVALID_NUMBER.getMessage());
}

// 유효성 검사는 Lotto 객체에 맡김
return new Lotto(numbers).getNumbers();
}
}
19 changes: 19 additions & 0 deletions src/main/java/lotto/machine/LottoSeller.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package lotto.machine;

import lotto.repository.Memory;

public class LottoSeller {

private static final int PRICE_PER_TICKET = 1000;
private static final String PRICE_INFORMATION = "[ERROR] 구입 금액은 1,000원 단위로 입력해야 합니다.";

public void sellLotto(int amount, Memory memory) {
if (amount % PRICE_PER_TICKET != 0) {
throw new IllegalArgumentException(PRICE_INFORMATION);
}
int ticketCount = amount / PRICE_PER_TICKET;

// Memory에 티켓 개수 저장
memory.saveTicketCount(ticketCount);
}
}
54 changes: 54 additions & 0 deletions src/main/java/lotto/machine/WinningSystem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package lotto.machine;

import lotto.constant.Rank.RankEnum;
import lotto.repository.Memory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WinningSystem {
private final Memory memory;

public WinningSystem(Memory memory) {
this.memory = memory;
}

// Memory에서 저장된 로또 티켓과 당첨 번호를 비교하여 Rank 계산 및 수익률 반환
public Map<RankEnum, Integer> checkWinning() {
List<List<Integer>> tickets = memory.getGeneratedNumbers();
List<Integer> winningNumbers = memory.getWinningNumbers();
int bonusNumber = memory.getBonusNumber();

Map<RankEnum, Integer> matchCount = new HashMap<>();
int totalPrize = 0;

// 각 티켓을 순회하며 당첨 결과 계산
for (List<Integer> ticket : tickets) {
int match = (int) ticket.stream().filter(winningNumbers::contains).count();
boolean matchBonus = ticket.contains(bonusNumber);
RankEnum rank = findRank(match, matchBonus);

matchCount.put(rank, matchCount.getOrDefault(rank, 0) + 1);
totalPrize += rank.getPrize(); // 당첨 금액 합산
}

memory.setTotalPrize(totalPrize); // Memory에 총 당첨 금액 저장
return matchCount; // 당첨 통계 반환
}

// Rank 계산 로직
private RankEnum findRank(int matchCount, boolean matchBonus) {
return java.util.Arrays.stream(RankEnum.values())
.filter(rank -> rank.getMatchCount() == matchCount && rank.isMatchBonus() == matchBonus)
.findFirst()
.orElse(RankEnum.NONE);
}

// 수익률 계산만 하고 반환
public double calculateProfitRate(int purchaseAmount) {
int totalPrize = memory.getTotalPrize();
double profitRate = ((double) totalPrize / purchaseAmount) * 100;
return Math.round(profitRate * 10) / 10.0; // 소수점 둘째 자리에서 반올림
}
}
58 changes: 58 additions & 0 deletions src/main/java/lotto/repository/Memory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package lotto.repository;

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

public class Memory {
private int ticketCount;
private List<List<Integer>> generatedNumbers = new ArrayList<>();
private List<Integer> winningNumbers;
private int bonusNumber;
private int totalPrize = 0; // 총 상금

// 티켓 개수 저장
public void saveTicketCount(int ticketCount) {
this.ticketCount = ticketCount;
}

// 티켓 개수 가져오기
public int getTicketCount() {
return ticketCount;
}

// 로또 번호 저장
public void saveGeneratedNumbers(List<Integer> numbers) {
this.generatedNumbers.add(numbers);
}

// 생성된 로또 번호 가져오기
public List<List<Integer>> getGeneratedNumbers() {
return generatedNumbers;
}

// 당첨 번호 저장
public void saveWinningNumbers(List<Integer> winningNumbers, int bonusNumber) {
this.winningNumbers = winningNumbers;
this.bonusNumber = bonusNumber;
}

// 저장된 당첨 번호 가져오기
public List<Integer> getWinningNumbers() {
return winningNumbers;
}

// 보너스 번호 가져오기
public int getBonusNumber() {
return bonusNumber;
}

// 총 상금 가져오기
public int getTotalPrize() {
return totalPrize;
}

// 총 상금 저장
public void setTotalPrize(int totalPrize) {
this.totalPrize = totalPrize;
}
}
Loading