[인프런 워밍업 클럽 - 스터디 0기 BE] 과제 #5

seolbin park·2024년 2월 23일

~제시된 코드를 클린 코드로 고치기~


[제시된 코드]


[고친 코드]

public class Main {
    private static final int DICE_SIDES = 6; //주사위가 1~6까지만 있는 경우

    public static void main(String[] args) throws IOException {
        System.out.print("숫자를 입력하세요 : ");
        Scanner scanner = new Scanner(System.in);
        int numberOfThrows = scanner.nextInt(); //주사위를 몇 번 던질지

        int[] results = rollDice(numberOfThrows);

        printResults(results);
    }

    //해당 숫자만큼 주사위를 던져, 각 숫자가 몇 번 나왔는지 알려주는 메소드
    private static int[] rollDice(int numberOfThrows) {
        int[] diceCounts = new int[DICE_SIDES];

        for (int i = 0; i < numberOfThrows; i++) {
            int result = (int) (Math.random() * DICE_SIDES) + 1;
            diceCounts[result - 1]++;
        }

        return diceCounts;
    }

    //각 숫자가 몇 번 나왔는지 printf
    private static void printResults(int[] results) {
        for (int i = 0; i < results.length; i++) {
            int number = i + 1;
            System.out.printf("%d는 %d번 나왔습니다.\n", number, results[i]);
        }
    }
}


참고

https://inf.run/XKQg

0개의 댓글