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
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
*/
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.
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;
}
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;
replace
int roll = r.nextInt();
with
int roll = r.nextInt(nSides);