<aside> 👉 코드를 리팩토링해서 클린 코드를 만들어보자
</aside>
<aside> ⚠️ 입력 받은 숫자만큼 주사위를 던져 눈금이 몇 번 나왔는지 출력하는 프로그램
</aside>
// DiceBeforeRefactor.java
package com.inflearn.Inflearn.Study.day05;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DiceBeforeRefactor {
public static void main(String[] args) throws IOException {
System.out.print("숫자를 입력하세요 : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
int d1 = 0, d2 = 0, d3 = 0, d4 = 0, d5 = 0, d6 = 0;
for (int i = 0; i < count; i++) {
double randomDiceNumber = (Math.random() * 6);
if (randomDiceNumber >= 1 && randomDiceNumber < 2) {
d1++;
} else if (randomDiceNumber >= 2 && randomDiceNumber < 3) {
d2++;
} else if (randomDiceNumber >= 3 && randomDiceNumber < 4) {
d3++;
} else if (randomDiceNumber >= 4 && randomDiceNumber < 5) {
d4++;
} else if (randomDiceNumber >= 5 && randomDiceNumber < 6) {
d5++;
} else if (randomDiceNumber >= 6 && randomDiceNumber < 7) {
d6++;
}
}
System.out.printf("1은 %d번 나왔습니다. \\n", d1);
System.out.printf("2은 %d번 나왔습니다. \\n", d2);
System.out.printf("3은 %d번 나왔습니다. \\n", d3);
System.out.printf("4은 %d번 나왔습니다. \\n", d4);
System.out.printf("5은 %d번 나왔습니다. \\n", d5);
System.out.printf("6은 %d번 나왔습니다. \\n", d6);
}
}
View 단
// InputView.java
package com.inflearn.Inflearn.Study.day05.view;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputView {
public static int readInput() throws IOException {
System.out.print("숫자를 입력하세요 : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
return count;
}
}
// OutputView.java
package com.inflearn.Inflearn.Study.day05.view;
public class OutputView {
public static void printOutput(int[] dice) {
int len = dice.length;
for(int i = 1; i <= len - 1; i++) {
System.out.println(i + "은 " + dice[i] + "번 나왔습니다.");
}
}
}
Controller 단
// DiceController.java
package com.inflearn.Inflearn.Study.day05.controller;
import com.inflearn.Inflearn.Study.day05.view.InputView;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class DiceController {
static int[] dice = new int[7];
public void play() throws IOException {
int count = InputView.readInput();
for(int i = 0; i < count; i++) {
int num = extractNumber();
dice[num]++;
}
}
private int extractNumber() {
int num = (int) (Math.random() * 6);
return num;
}
}
Main
// DiceRefactor.java
package com.inflearn.Inflearn.Study.day05;
import com.inflearn.Inflearn.Study.day05.controller.DiceController;
import java.io.IOException;
public class DiceRefactor {
public static void main(String[] args) throws IOException {
DiceController diceController = new DiceController();
diceController.play();
}
}