Basic Random Rolling Dice Java

前端 未结 5 952
栀梦
栀梦 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
    */
    
    0 讨论(0)
  • 2021-01-05 11:46

    Random.nextInt() has unpredicable behaviour - it can produce all values possible for an integer, including negative numbers. Use Random.nextInt(numSides) instead - it will return an integer from [0,numSides) i.e. including 0 and excluding numSides. To get your desired functionality [1,numSides] use

    r.nextInt(numSides)+1;
    

    See here for more information.

    0 讨论(0)
  • 2021-01-05 11:48

    How about this as your rollDice method:

    public static int rollDice(int number, int nSides) {
        int count = 0;
        for(int i = 0; i < number; i++) {
            count += (int)(Math.random() * nSides) + 1;
        }
        return count;
    }
    
    0 讨论(0)
  • 2021-01-05 11:51

    When you use % on a negative number you get a negative number.

    In this case the solution is simple, use

    int roll = r.nextInt(nSides) + 1; // 1 to nSizes
    num += roll;
    
    0 讨论(0)
  • 2021-01-05 11:57

    replace
    int roll = r.nextInt();
    with

    int roll = r.nextInt(nSides);

    0 讨论(0)
提交回复
热议问题