과제 5

package com.group.libraryapp.controller.dice;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class DiceController {

    @GetMapping("/api/dice")
    public String dice(@RequestParam int tryCount, @RequestParam int diceCount) {
        int[] diceArray = rollDice(tryCount, diceCount);

        String ans = diceResult(diceArray);

        return ans;
    }

    private int[] rollDice(int tryCount, int diceCount) {
        int[] diceArray = new int[diceCount];

        for (int i = 0; i < tryCount; i++) {
            int index = (int) (Math.random() * diceCount);
            diceArray[index]++;
        }
        return diceArray;
    }

    private String diceResult(int[] diceArray) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < diceArray.length; i++) {
            String line = String.format("%d는 %d번 나왔습니다.\n", i+1, diceArray[i]);
            sb.append(line);
        }

        return sb.toString();
    }
}

댓글을 작성해보세요.

채널톡 아이콘