Skip to content
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
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ repositories {
dependencies {
compile('ch.qos.logback:logback-classic:1.2.3')
testCompile('junit:junit:4.12')
//testCompile('harcrest-all:org.hamcrest.hamcrest-all:1.3')
testCompile('org.assertj:assertj-core:3.9.0')
}
27 changes: 27 additions & 0 deletions src/main/java/Todo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## Todo List

- 금액 입력받기
- 금액에 맞는 로또 구입하기
done
- 각 로또에 맞는 번호 자동생성
- 숫자는 1 ~ 45 랜덤값
done
- 구입한 로또번호 출력
- 정렬하여 출력

- 잔액은 상점이 갖는다. 최대 구입가능한 로또만 구입함.
done

- 당첨될 로또번호 6개 입력
- 구매한 로또들의 당첨상황 확인
- 수익률 계산
- 당첨상황 및 수익률 출력


## Todo List
1. LottoClient 메소드

- 1) 로또결과 (로또 객체와 완전 상관없는 부분) 따로 빼고 클라이언트에서 호출
- 2) 네이밍
- 3) 유틸
- 4) 접근 제어
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

todo list 작성 💯

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

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

public class HitNumber {
final List<Integer> hitNumbers;
static final String DELIMITER = ", ";
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

클래스의 구현 순서는 다음과 같다. 다음 원칙에 따라 구현한다.

class A {
    상수(static final) 또는 클래스 변수
    인스턴스 변수
    생성자
    메소드
}


public HitNumber(String inputNumber) {
if (!isValid(inputNumber))
throw new IllegalArgumentException();
hitNumbers = Collections.unmodifiableList(
toIntList(split(inputNumber, DELIMITER)));
}


public static boolean isValid(String answer) {
String[] numbers = split(answer, DELIMITER);
return Arrays.asList(numbers)
.stream()
.allMatch(e -> validateNumber(e)) && numbers.length == LottoGenerator.LOTTO_NUMBER_COUNT;
}

private static boolean validateNumber(String number) {
int num = 0;
try {
num = toInt(number);
} catch (NumberFormatException e) {
return false;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

이 부분은 굳이 try/catch로 처리하지 않아도 되지 않을까?
그냥 exception throw하도록..
좀 과하다는 느낌이 듦

}
if (num > LottoGenerator.NUMBER_UPPER_BOUND || num < LottoGenerator.NUMBER_LOWER_BOUND) return false;

return true;
}

private static String[] split(String input, String delimiter) {
return input.split(delimiter);
}

private static List<Integer> toIntList(String[] inputStr) {
return Arrays.asList(inputStr).stream().map(e -> toInt(e)).collect(Collectors.toList());

}

private static int toInt(String number) {
return Integer.parseInt(number);
}

public int increment(int number){
if(hitNumbers.contains(number))
return 1;
return 0;
}
}
22 changes: 22 additions & 0 deletions src/main/java/lotto/InputUI.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package lotto;

import java.util.Scanner;

public class InputUI {
private static Scanner scanner = new Scanner(System.in);

public static int getForLottoMoney() {
System.out.println("구입금액을 입력해 주세요");
try {
return Integer.parseInt(scanner.nextLine());
} catch (Exception e) {
throw new IllegalArgumentException();
}
}

public static String getHitNumber() {
System.out.println("지난 주 당첨 번호를 입력해 주세요.");
return scanner.nextLine();
}

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

import java.util.List;

public class Lotto {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

HitNumber와의 차이점은??
같은 Lotto로 사용해도 되지 않나?

private List<Integer> lottoNumbers;

public Lotto()
{
this(LottoGenerator.generateNum());
}

private Lotto(List<Integer> lottoNumbers){
this.lottoNumbers = lottoNumbers;
}


public static Lotto getLottoByInput(List<Integer> lottoNumbers){
return new Lotto(lottoNumbers);
}

public int compareLotto(HitNumber hitNumber) {
int count = 0 ;
for(int number : lottoNumbers) {
count += hitNumber.increment(number);
}
return count;
}

@Override
public String toString() {
return lottoNumbers.toString();
}
}
114 changes: 114 additions & 0 deletions src/main/java/lotto/LottoClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package lotto;

import java.util.*;
import java.util.stream.Collectors;

public class LottoClient {
private static final int LOTTO_PRICE = 1000;
private static Map<Integer, Integer> resultAwardMap;
static {
LOTTO_AWARDS basicAwards = LOTTO_AWARDS.BASIC;
resultAwardMap = new TreeMap<Integer, Integer>();
resultAwardMap.put(3, basicAwards.getThree_correct());
resultAwardMap.put(4, basicAwards.getFour_correct());
resultAwardMap.put(5, basicAwards.getFive_correct());
resultAwardMap.put(6, basicAwards.getSix_correct());
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

convention 위반
변수 이름, 메소드 이름에 "_"를 사용하지 않는다.
camel 컨벤션을 따른다.

}

private enum LOTTO_AWARDS {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

enum을 적절하게 사용하지 못하고 있는 느낌이다.
enum을 어떤 용도로 사용할 것인지 좀 더 고민해 보면 좋겠다.

BASIC(5000, 50000, 1500000, 2000000000);

private int three_correct;
private int four_correct;
private int five_correct;
private int six_correct;

LOTTO_AWARDS(int three_correct, int four_correct, int five_correct, int six_correct) {
this.three_correct = three_correct;
this.four_correct = four_correct;
this.five_correct = five_correct;
this.six_correct = six_correct;
}

public int getThree_correct() {
return three_correct;
}

public int getFour_correct() {
return four_correct;
}

public int getFive_correct() {
return five_correct;
}

public int getSix_correct() {
return six_correct;
}
}

public static void main(String[] args) {
run();
}

private static void run() {
printResult(makeLottoes());
}

private static List<Lotto> makeLottoes(){
Money money = new Money(InputUI.getForLottoMoney());
List<Lotto> lottoes = new LottoFactory().createLotto(maxLottoToBuy(money));

ResultUI.printBuyedLottoes(
lottoes.stream()
.map(x -> x.toString())
.collect(Collectors.toList()));
return lottoes;
}

private static void printResult(List<Lotto> lottoes){
HitNumber hitNumber = new HitNumber(InputUI.getHitNumber());

List<Integer> results = calculateResults(lottoes, hitNumber);

for (Integer numOfHits : resultAwardMap.keySet()) {
ResultUI.printResultStatics(
numOfHits,
resultAwardMap.get(numOfHits),
Collections.frequency(results, numOfHits)
);
}
ResultUI.printBenefitRate(calculateBenefitRate(lottoes, hitNumber));
}


public static double calculateBenefitRate(List<Lotto> lottoes, HitNumber hitNumber) {
List<Integer> lottoResults = calculateResults(lottoes, hitNumber);
double sum = getSum(lottoResults);
return floor(sum / (lottoResults.size() * LOTTO_PRICE) * 100);
}

private static double getSum(List<Integer> lottoResults) {
return (double) lottoResults.stream()
.filter(x -> resultAwardMap.containsKey(x))
.mapToInt(x -> resultAwardMap.get(x))
.sum();
}

private static double floor(double target) {
int intTarget = (int) (target * 10);
return intTarget / 10.0;
}

private static List<Integer> calculateResults(List<Lotto> lottoes, HitNumber hitNumber) {
List<Integer> results = new ArrayList<Integer>();
for (Lotto lotto : lottoes) {
results.add(lotto.compareLotto(hitNumber));
}
return results;
}

public static int maxLottoToBuy(Money money) {
return money.getMoney() / LOTTO_PRICE;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

수익률을 계산하고 결과 처리를 담당하는 새로운 객체를 추가하는 것은 어떨까?
LottoClient가 너무 많은 일을 하고 있는 것 같다.

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

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

public class LottoFactory {
LottoGenerator generator;

public LottoFactory(){
this.generator = new LottoGenerator();
}
public List<Lotto> createLotto(int maxLottoCount) {
List<Lotto> newLottoes = new ArrayList<Lotto>();
for (int i = 0; i < maxLottoCount; i++) {
newLottoes.add(new Lotto());
}
return newLottoes;
}
}
27 changes: 27 additions & 0 deletions src/main/java/lotto/LottoGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package lotto;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class LottoGenerator {
public static final int LOTTO_NUMBER_COUNT = 6;
public static final int NUMBER_LOWER_BOUND = 1;
public static final int NUMBER_UPPER_BOUND = 45;
static List<Integer> validNumberSet;

static {
validNumberSet = new ArrayList<Integer>();
for (int i = NUMBER_LOWER_BOUND ; i < NUMBER_UPPER_BOUND; i++) {
validNumberSet.add(i + 1);
}
}

public static List<Integer> generateNum() {
Collections.shuffle(validNumberSet, new Random(System.currentTimeMillis()));
List<Integer> result = new ArrayList(validNumberSet.subList(0, LOTTO_NUMBER_COUNT));
Collections.sort(result);
return result;
}
}
16 changes: 16 additions & 0 deletions src/main/java/lotto/Money.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package lotto;

public class Money {
private int money;

public Money(int money) {
if (money < 0) {
throw new IllegalArgumentException();
}
this.money = money;
}

public int getMoney() {
return money;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Money가 더 많은 일을 할 수 있지 않을까?
몇 장의 Lotto를 구매할 수 있는지, 수익율 등도 이곳에서 처리할 수 있지 않을까?
돈과 관련된 모든 로직을 구현한다면??

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

import java.util.List;

public class ResultUI {

public static void printBuyedLottoes(List<String> lottoes) {
System.out.printf("%d개를 구매했습니다.\n", lottoes.size());
for (String lotto : lottoes)
System.out.println(lotto);
}

public static void printResultStatics(int numOfHits, int prize, int numOfPrizes) {
System.out.printf("%d개 일치 (%d원)- %d개\n", numOfHits, prize, numOfPrizes);
}

public static void printBenefitRate(double benefitRate) {
System.out.printf("총 수익률은 %.1f%% 입니다.\n", benefitRate);
}
}
Loading