Dice Rolling) Write an application to simulate the rolling of two dice. The application should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums.
Figure below shows the 36 possible combinations of the two dice. Your application should roll the dice 36,000 times. Use a one_dimensional array to keep track of the number of times each possible sum appears. Display the results in tabular format. Determine whether the totals are reasonable (e.g., there are six ways to roll a 7, so approximately one-sixth of the rolls should be 7).
Hints:
Keep track of how many times each total (2 through 12) occurs. This total is used to calculate the percentage of the time that each total occurs.
Define a loop that iterates 36,000 times. During each iteration, roll the dice, calculate the total and update the count for the particular total in the array.
Create an array large enough that you can use the sum of the dice as the index into the array.
Fig. below | The 36 possible outcomes of rolling two dice.
|
The Output Result Sum Frequency Percentage 2 1034 2.87 3 1987 5.52 4 3028 8.41 5 3881 10.78 6 4912 13.64 7 6135 17.04 8 5060 14.06 9 4032 11.20 10 2965 8.24 11 2003 5.56 12 963 2.68 |
Be sure your programs compile and run without error.
§ Include a comment at the beginning of each source file you submit that includes your name and the lab date.
§ Names for variables and other program components should be chosen to help convey the meaning of the variable.
import java.util.Random;
public class HelloWorld
{
public static void main(String[] args)
{
Random r = new Random();
int[] totals = new int[36000];
int[] count = new int[11];
double[] per = new double[11];
for(int i = 0; i < 36000; i++)
totals[i] = Roll_Dice(r) + Roll_Dice(r);
for(int i = 0; i < 11; i++)
for(int j = 0; j < 36000; j++)
if(totals[j] == (i+2))
count[i]++;
for(int i = 0; i < 11; i++)
per[i]=((double)count[i]/360);
System.out.println("SUM\tFREQUENCY\tPERCENTAGE");
for(int i = 0; i < 11; i++)
{
System.out.print((i+2)+"\t"+ count[i]);
System.out.printf("\t\t%.2f\n", per[i]);
}
}
public static int Roll_Dice(Random r)
{
return(r.nextInt(6)+1);
}
}
Get Answers For Free
Most questions answered within 1 hours.