Close
Close

How do I get it to print the Sum and Percentage?

   Bethany Belbin

So I have been given the question below and below that is my code so far. I am having a hard time trying to get it to print the ‘Sum’ and the ‘Percentage.’ Does anyone have any suggestions?

 Write a program to simulate the rolling of two dice. The program should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums.  Your application should roll the dice 36,000 times. Use a one dimensional array to keep track of the number of times each possible sum appears.

Display the results in tabular format. Determine whether the totals are reasonable (e.g., here are six ways to roll a 7, so approximately one-sixth of the rolls should be 7). 

Sample output:

Sum   Frequency  Percentage

  2        1027        2.85

  3        2030        5.64

  4        2931        8.14

  5        3984       11.07

  6        5035       13.99

  7        5996       16.66

  8        4992       13.87

  9        4047       11.24

 10        2961        8.23

 11        1984        5.51

 12        1013        2.81

import java.security.SecureRandom;
public class DiceSum {
    public static void main(String[] args) {
       
        SecureRandom random = new SecureRandom();

        int dice1, dice2;
        int [] frequency = new int [13];
        int [] rolls = new int [13];
        int sum;
        int percentage;

        for (int i = 0; i <= 36000; i++) { // runs 36000 times
            

            dice1 = random.nextInt(6)+1; // generates a random number
            dice2 = random.nextInt(6)+1;
            
            frequency[dice1+dice2]++;
        
            sum = dice1 + dice2; // creates the sum of dice 1 and dice 2
   
        
        }
        
        System.out.printf("Sum\t Frequency\t Percentage\n");
       

        for (int i = 2; i < frequency.length; i++) {

            System.out.printf("%d\t\n",+i+frequency[i]);
        
        
        } // end of for loop
      

    } // end of main
    
} // end of class


Answers

  •   

    There is just a small error in the format of your printf. Correct it to:

    System.out.printf("%d\t%d\n",i,frequency[i]);
    

    Hopefully, you can also calculate the percentage.


    • Thats perfect! Thank you!
      - Bethany Belbin

Ask Yours
Post Yours
Write your answer