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
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