public class Dice {
private int numberOfSides;
public Dice(int numberOfSides) {
this.numberOfSides = numberOfSides;
}
public int roll() {
return (int)(Math.random() * numberOfSides + 1);
}
}
주사위 자체에 대한 속성과 기능을 담당하는 코드는 Dice 클래스를 만들어 분리했다.
numberOfSides
라는 멤버변수를 두었다.import java.util.Scanner;
public class PracticeMain {
public static void main(String[] args) {
final int NUMBER_OF_SIDES = 6;
int rollCount = getUserInputInt();
Dice dice = new Dice(NUMBER_OF_SIDES);
int[] countsOfNumbers = new int[NUMBER_OF_SIDES];
for (int i = 0; i < rollCount; i++) {
countsOfNumbers[dice.roll()-1]++;
}
printNumberCount(countsOfNumbers);
}
public static int getUserInputInt() {
System.out.print("숫자를 입력하세요 : ");
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
scanner.close();
return number;
}
public static void printNumberCount(int[] numbers) {
int unitsDigit;
for (int i = 0; i < numbers.length; i++) {
unitsDigit = (i + 1) % 10;
if (unitsDigit == 0 || unitsDigit == 1 || unitsDigit == 3 ||
unitsDigit == 6 || unitsDigit == 7 || unitsDigit == 8) {
System.out.printf("%d은 %d번 나왔습니다.\\n", i+1, numbers[i]);
}
else {
System.out.printf("%d는 %d번 나왔습니다.\\n", i+1, numbers[i]);
}
}
}
}
NUMBER_OF_SIDES
를 정의하여 코드의 가독성을 높이고, 추후 주사위의 숫자 범위가 달라지더라도 코드 수정을 적게할 수 있도록 했다.