PDA

View Full Version : Is there a way to exclude 0 when using Math.random()?


clharri23
11-19-2009, 06:10 AM
I am trying to make this program that serves as a Dice Roll Simulation. "The program simulates rolling two dice 100,000 times and displays the number of occurrences of each sum from 2 to 12" (Bravaco and Simonson 2010). The problem I am having is that a dice only has 6 different values ranging from 1 - 6. How do I manipulate the Math.random() method so that it only returns random numbers from 1- 6 and not 0 - 6? This problem comes from the text by Ralp Bravaco and Shai Simonson, "Java Programming: From the Ground Up." Here is the code, and thanks for your help:


public class DiceRollSimulation
{
public static void main(String [] args)
{
final int NUM_ROLLS = 100000; //rolls dice 100,000 times

String output = ("Sum\tOccurences after " + NUM_ROLLS + " Rolls");
int diceOne = 0, diceTwo = 0, diceSum = 0;
int [] sum = new int[13];

for(int i = 0; i < 100000; i++)
{
diceOne = (int)(7*Math.random());
diceTwo = (int)(7*Math.random());
diceSum = diceOne + diceTwo;

if(diceSum >= 2 && diceSum <= 12)
{
sum[diceSum]++;
}
}

System.out.println(output);

for(int j = 2; j < sum.length; j++)
{
System.out.println(" " + j + "\t\t" + sum[j] + "\n");
}

} //end main
} //end class

BubikolRamios
11-19-2009, 06:15 AM
diceOne = (int)(6*Math.random() +1);

Fou-Lu
11-19-2009, 06:21 AM
The easiest way is to use the Random class. The nextInt method returns 0 (inclusive) to n (exclusive). So, you'd use like so:

Random rand = new Random();
// Some stuff here
diceOne = rand.nextInt(6) + 1;
...

And using the math class, you can acheive the same with a similar logic:

diceOne = (int)(Math.random() * 6) + 1

And that is supposed to be 6 yes, Math.random is [0.0, 1.0)

clharri23
11-19-2009, 06:34 AM
Thanks fellas.