如何在Yahtzee中重新掷骰子

时间:2017-12-17 18:54:27

标签: java

我是一名非常初学的程序员,而且我仍然坚持如何在我的程序中重新掷骰子。我正在研究的项目是Yahtzee。在Yahtzee,你掷5个骰子,你可以选择要重新掷骰子(' r')以及要保留的骰子(' k')。总之,我试图滚2次。 包yahtzee1;

import java.util.Scanner;

public class Yahtzee1 {
    /**
     * Allows the get information from the user like to keep or reroll
     * @param prompt
     * @return 
     */
     public static char getcharFromUser(String prompt) { 
        Scanner sc = new Scanner(System.in);
        System.out.println(prompt);
        char c = sc.next().charAt(0);
        return c;
     }

    /**
     * generate 5 random numbers from 1 to 6, inclusive
     * @param dice array to store the numbers
     */
    public static void roll(int[] dice) {
        for (int i = 0; i < 5; i++) {
            dice[i] = (int) (Math.random() * 6 + 1);
        }
    }

    /**
     * generate 5 random numbers from 1 to 6, inclusive
     *
     * @param dice array to store the numbers
     */
    public static void printDice(int[] dice) {
        for (int i = 0; i < 5; i++) {
            System.out.print(dice[i]);
        }
    }

   /**
    * After the 5 dice are "rolled" user picks which dice to re-roll or keep
    * @param dice
    * @param option 
    */
    public static void reRoll(int[] dice, String option) {

        //help here
    }

    /**
     * 
     * @param dice 
     */
    public static void playRound(int [] dice){
       for (int i = 0; i < 2;i++){
            reRoll(dice, option);

            roll(dice);

            printDice(dice);
        }
    }
    /**
     * play Yahtzee
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] dice = new int[6];
        playRound(dice);
    }


}

我的代码中需要帮助的部分是reRoll方法。

1 个答案:

答案 0 :(得分:0)

您可以这样做:

public static void reRoll(int[] dice, String option) {
    //Change the split parameter to whatever you need the delimiter to be
    for(String numString: option.split(" ")){ 
        int die = Integer.parseInt(numString);
        dice[die-1] = (int) (Math.random() * 6 + 1);
    }

}

public static void playRound(int [] dice){

    roll(dice);

    printDice(dice);

    Scanner sc = new Scanner(System.in);

   for (int i = 0; i < 2;i++){

       System.out.print("Enter dice to reroll: ");

       String option = sc.nextLine();

        reRoll(dice, option);

        printDice(dice);
    }

   sc.close();
}