Instructions: Create a new Java file called Dice.java Simulate the rolling of 2
ID: 665898 • Letter: I
Question
Instructions: Create a new Java file called Dice.java Simulate the rolling of 2 dice. Do that by creating one single object of type Random and by reusing it to roll the first die and then the second die. Once both dice have been rolled calculate the sum of the two values. Use a one - dimensional integer array to count how often each sum appears. When rolling two dice the sum will be a value from 2 - 12. However, not every sum has the same probability of being rolled. E.g.: There are three ways to roll a sum of 4, six ways to roll a sum of 7 but only one way to roll a sum of 12. Learning Purpose: Practice Random number generation Use of arrays Formatted output Roll the two dice 36,000 times. Display the results in a tabular format like in the sample output. Start with a header line (Sum, Fequency, and Percentage) and list the numbers in right aligned columns. The percentage should display only one digit after the decimal point. Hint: In order to output % within a format string write %% Recommendation: Check whether the results are reasonable (e.g. the sum 7 should be rolled about 1/6 of the time)Explanation / Answer
public class RollTheDice {
/* This program simulates rolling a pair of dice.
The number that comes up on each die is output,
followed by the total of the two dice.
*/
public static void main(String[] args) {
int die1; // The number on the first die.
int die2; // The number on the second die.
int roll; // The total roll (sum of the two dice).
int i;
int sumtwo =0;
int sumthree=0;
int sumfour=0;
int sumfive=0;
int sumsix=0;
int sumseven=0;
int sumeight=0;
int sumnine=0;
int sumten=0;
int sumeleven=0;
int sumtwelve=0;
for (i=0;i<36000;i++)
{
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
if (roll == 2)
sumtwo++;
else if (roll == 3)
sumthree++;
else if (roll == 4)
sumfour++;
else if (roll == 5)
sumfive++;
else if (roll == 6)
sumsix++;
else if (roll == 7)
sumseven++;
else if (roll == 8)
sumeight++;
else if (roll == 9)
sumnine++;
else if (roll == 10)
sumten++;
else if (roll == 11)
sumeleven++;
else
sumtwelve++;
}
System.out.println("sum frequency percentage");
System.out.println("2 "+sumtwo+" "+(sumtwo*100/36000));
System.out.println("3 "+sumthree+" "+(sumthree*100/36000));
System.out.println("4 "+sumfour+" "+(sumfour*100/36000));
System.out.println("5 "+sumfive+" "+(sumfive*100/36000));
System.out.println("6 "+sumsix+" "+(sumsix*100/36000));
System.out.println("7 "+sumseven+" "+(sumseven*100/36000));
System.out.println("8 "+sumeight+" "+(sumeight*100/36000));
System.out.println("9 "+sumnine+" "+(sumnine*100/36000));
System.out.println("10 "+sumten+" "+(sumten*100/36000));
System.out.println("11 "+sumeleven+" "+(sumeleven*100/36000));
System.out.println("12 "+sumtwelve+" "+(sumtwelve*100/36000));
} // end main()
} // end class