Basic Random Rolling Dice Java

前端 未结 5 951
栀梦
栀梦 2021-01-05 11:31

I am trying to write a method rollDice(int number, int nSides) which returns the total result of rolling the number dice with nSides sides.

So for example rollDice(3

5条回答
  •  伪装坚强ぢ
    2021-01-05 11:39

    You only need to initialize Random r and int roll once each so I have removed them from the loop. The nextInt(int) method picks an integer from and including 0 to but not including the int. This is known as 0 (inclusive) to int (exclusive), so you have to add 1 to adjust the range to the die. You seem to have known that though I don't know why you used %. Using * to multiply would give you the same number for all the dice which I don't believe you mean to do. Here is one possible implementation of your class:

    import java.util.Random;
    
    public class Dice {
    
        public static  int rollDice(int number, int nSides)
        { 
            int num = 0;
            int roll = 0;
            Random  r = new Random(); 
            if(nSides >=3) 
            { 
                for(int i = 0; i < number; i++)
                { 
                    roll = r.nextInt(nSides)+1;
                    System.out.println("Roll is:  "+roll);
                    num = num + roll; 
                } 
            } 
            else
            { 
                System.out.println("Error num needs to be from 3"); 
            } 
            return num;  
        } 
    
        public static void main(String[] args)
        {
            System.out.println("Total is: "+rollDice(3, 6));
        }
    }
    /*
    Roll is:  4
    Roll is:  1
    Roll is:  2
    Total is: 7
    */
    

提交回复
热议问题