create a new java file called dice.java simulate ... Question: Create a new Java
ID: 3813432 • Letter: C
Question
create a new java file called dice.java simulate ... Question: Create a new Java file called Dice.java... Bookmark 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 rollthe 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 everysum 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 onlyone way to roll a sum of 12. Roll the two dice 36,000 times. Display the results in a tabular format like in the sample output. Start with aheader line ( Sum, Fequency, and Percentage) and list the numbers in rightaligned 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
HI, Please find my implementation.
Please let me know in case of any issue.
import java.util.Random;
public class Dice {
public int getValue(){
Random rand = new Random();
return rand.nextInt(6)+1;
}
public static void main(String[] args) {
// creating an array
int sum[] = new int[13];
// creating two dice
Dice dice1 = new Dice();
Dice dice2 = new Dice();
for(int i=1; i<36000; i++){
int roll1 = dice1.getValue();
int roll2 = dice2.getValue();
sum[roll1+roll2]++; // increasing the count
}
// finding the total
double total = 0;
for(int i=2; i<13; i++)
total = total + sum[i];
System.out.println("Sum Frequency Percentage");
for(int i=2; i<13; i++){
System.out.println(i+" "+sum[i]+" "+String.format("%.4f", (sum[i]/total)*100));
}
}
}
/*
Sample run:
Sum Frequency Percentage
2 960 2.6667
3 1975 5.4863
4 3016 8.3780
5 4060 11.2781
6 5022 13.9504
7 6005 16.6810
8 5054 14.0393
9 3997 11.1031
10 2942 8.1724
11 1939 5.3863
12 1029 2.8584
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.