Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Random Rolling Dice Java

Tags:

java

random

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, 6) should return the result of rolling 3 six-sided dice (adding to a number between 3 and 18 inclusive).

Below method returns negative numbers when I type 1 for int number what do I need to do to fix this?

public static  int rollDice(int number, int nSides) {
    int num = 0;
      if(nSides >=3)
    {
      for(int i = 0; i < number; i++){
       Random  r = new Random(); 
       int roll = r.nextInt();
       num = num + (roll % nSides)+1;

      }
    }
      else{
          System.out.println("Error num needs to be from 3");

    }
    return num; 
} 
like image 735
user1721548 Avatar asked Oct 12 '12 13:10

user1721548


2 Answers

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.

like image 161
Patrick White Avatar answered Oct 05 '22 10:10

Patrick White


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
*/
like image 25
apcris Avatar answered Oct 05 '22 10:10

apcris