Roll a six-sided die 6000 times in Java

Java 8Object Oriented ProgrammingProgramming

In order to roll a six sided die 6000 times in Java, we need to the nextInt() statement with decision making statements.

The nextInt() method returns the next random integer value from this random number generator sequence.

Declaration − The java.util.Random.nextInt() method is declared as follows −

public int nextInt()

Let us see a program to roll a six sided die 6000 times −

Example

 Live Demo

import java.util.Random;
public class Example {
   public static void main(String args[]) {
      Random rd = new Random(); // random number generator
      int freq[] = new int[6]; // creating an array to compute frequency of each face
      int val;
      int chance = 1;
      // rolling the dice 6000 times
      while(chance <= 6000){
         val = 1 + rd.nextInt(6); // generates integers from 1 to 6
         switch (val) {
            case 1:
               ++freq[0];
               break;
            case 2:
               ++freq[1];
               break;
            case 3:
               ++freq[2];
               break;
            case 4:
               ++freq[3];
               break;
            case 5:
               ++freq[4];
               break;
            case 6:
               ++freq[5];
               break;
         }
         chance++;
      }
      for(int i = 1; i <= 6; i++){
         System.out.println("Side: " + i + "-> Frequency : " + freq[i - 1]);
      }
   }
}

Output

Side: 1-> Frequency: 987
Side: 2-> Frequency : 971
Side: 3-> Frequency : 1057
Side: 4-> Frequency : 979
Side: 5-> Frequency : 982
Side: 6-> Frequency : 1024
raja
Updated on 25-Jun-2020 14:51:04

Advertisements