Question: (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
(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 the least frequent. Figure 7.28 shows the 36 possible combinations of the two dice. Your application should roll the dice 36,000,000 times. Use a one-dimensional array to tally the number of times each possible sum appears. Display the results in tabular format.
code to get the random number class imported
import java.util.Random;
code to declare a variable of type random
Random randomNumbers = new Random();
using it
variable = 1 + randomNumbers.nextInt(6);
***The codes for the problem
public class SumDice {
public static void main(String[] args) {
//variables int dice1; int dice2; int arr[]=new int[11]; int count=0;
//Printing result of Dice Rolled 36,000,000 times for(int i=0;i<36000000;i++) { int sum= RollDice(); //Calling the method RollDice to calculate the sum if(sum==2) // Storing the sum in array { arr[0]++; } else if(sum==3) { arr[1]++; } else if(sum==4) { arr[2]++; } else if(sum==5) { arr[3]++; } else if(sum==6) { arr[4]++; } else if(sum==7) { arr[5]++; } else if(sum==8) { arr[6]++; } else if(sum==9) { arr[7]++; } else if(sum==10) { arr[8]++; } else if(sum==11) { arr[9]++; } else if(sum==12) { arr[10]++; } } for(int j=0;j<6;j++) { for(int k=count;k<6+j;k++) { System.out.print(" "+arr[k]); } System.out.println(); count++; } } public static int RollDice() { int dice1=(int)(Math.random()*6+1); //Rolling Dice to generate random Number int dice2=(int)(Math.random()*6+1); int sum= dice1 + dice2; //Adding the random numbers of both the dice return sum; }
***** The problem and the code are above. Can someone cleraly explian the code in details so i can understand the code. Thank you for your time.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
