File Edit View WindowHelp open a a B | [ 11 / 1 | | 95.4% E | Asi Tools Fill & S
ID: 665959 • Letter: F
Question
File Edit View WindowHelp open a a B | [ 11 / 1 | | 95.4% E | Asi Tools Fill & Sign Comment Learning Purpose: Instructions: Random number generation Create a new Java file called Dice.java Use of arrays Formatted output . 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. Sample Output: Sum Frequency Percentage Use a one-dimensional integer array to count how often each sum appears. 1003 1980 2955 4123 4908 6014 4940 3932 3100 2034 1011 2.8% 5.5 8.2% 11.5% 13.6% 16 . 7% 13 . 7% 10·5% 8.6 5·79 2.8% 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 10 12 10 10 9 10 1 12 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
import java.util.Random;
public class PairOfDice {
public static void main(String[] args){
Random rand=new Random();
int[] arr=new int[13];
double[] per=new double[13];
for(int i=0;i<arr.length;i++){
arr[i]=0;
}
int die1,die2,sum;
for(int i=0;i<36000;i++){
die1 = rand.nextInt(6) + 1;
die2 = rand.nextInt(6) + 1;
sum=die1+die2;
if(sum==2){
arr[2]=arr[2]+1;
}else if(sum==3){
arr[3]=arr[3]+1;
}else if(sum==4){
arr[4]=arr[4]+1;
}else if(sum==5){
arr[5]=arr[5]+1;
}else if(sum==6){
arr[6]=arr[6]+1;
}else if(sum==7){
arr[7]=arr[7]+1;
}else if(sum==8){
arr[8]=arr[8]+1;
}else if(sum==9){
arr[9]=arr[9]+1;
}else if(sum==10){
arr[10]=arr[10]+1;
}else if(sum==11){
arr[11]=arr[11]+1;
}else if(sum==12){
arr[12]=arr[12]+1;
}
}
double f;
for(int i=2;i<13;i++){
f=((double)arr[i]/36000);
per[i]=f*100;
}
System.out.println("Sum Frequency Percentage ");
for(int j=2;j<13;j++){
System.out.println(j+" "+arr[j]+" "+per[j]);
}
}
} // end class PairOfDice
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.