41.4k views
2 votes
Write code 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.

User Alexw
by
6.0k points

1 Answer

7 votes

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\t\toccurrences\t\tfrequency");

for(i=1; i<7; i++) {

System.out.print(i+"\t\t"+arr[i]+"\t\t\t");

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

*/

Step-by-step explanation:

User Piyush Bhati
by
5.6k points