Write code in Java to simulate rolling a six-sided die. A six-sided die has the
ID: 3730029 • Letter: W
Question
Write code in Java to simulate rolling a six-sided die. A six-sided die has the values 1-6 on its faces. The program first asks user for the number of rolls and then rolls the die for the specified times. The program displays the face values, the number of occurrences of each value, and the frequency of each value in a neat tabular format. Use an int array to store the number of occurrences of 6 values and a double array to store the frequency of 6 values. Display 5 decimal places for floating-point values.
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
public class Dice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("how many times want to roll: ");
int n = sc.nextInt();
Random ran = new Random();
int[] arr = new int[7];
int i = 0;
while(i < n) {
int r = ran.nextInt(6)+1; //1-6
arr[r]++;
i++;
}
double[] frequency = new double[7];
for(i=1; i<7; i++) {
frequency[i] = arr[i]/(double)n;
}
System.out.println("Number occurrences frequency");
for(i=1; i<7; i++) {
System.out.print(i+" "+arr[i]+" ");
System.out.println(String.format("%.5f", frequency[i]));
}
}
}
/*
Sample run:
how many times want to roll: 400
Number occurrences frequency
1 69 0.17250
2 71 0.17750
3 72 0.18000
4 59 0.14750
5 62 0.15500
6 67 0.16750
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.