Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Practice Random number generation Use of arrays Formatted output Zip up Dic

ID: 3813833 • Letter: J

Question

Java

Practice Random number generation Use of arrays Formatted output Zip up Dice.java and turn it in via Virtual Campus. 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 roll the 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 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. 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. 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.

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("%.1f", (sum[i]/total)*100)+"%");

       }

      

   }

}

/*

Sample run:

Sum       Frequency       Percentage

2       1006           2.8%

3       2089           5.8%

4       3040           8.4%

5       3980           11.1%

6       4975           13.8%

7       5851           16.3%

8       4900           13.6%

9       4035           11.2%

10       3074           8.5%

11       2095           5.8%

12       954           2.7%

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote