Using the Random Class in Java to Roll Dices

Problem:

Write an application that simulates the rolling of two dice. The application should use an object of a 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. The sum of the values will vary from 2 to 12 with 7 being the most frequent sum, and 2 and 12 the less frequent sum. Your application should roll the dice 3600 times. Use one dimensional array to tally the number of times each possible sum appears. Display the result for example: 36 played that had the sum of 11.


Output:

101 played that had the sum of 2
179 played that had the sum of 3
305 played that had the sum of 4
437 played that had the sum of 5
515 played that had the sum of 6
606 played that had the sum of 7
493 played that had the sum of 8
377 played that had the sum of 9
303 played that had the sum of 10
182 played that had the sum of 11
102 played that had the sum of 12


Solution:

import java.util.Random;

public class Problem
{
  public static void main (String[] args)
  {
    Random d = new Random();
    int[] nums = new int[11];
    int a =0,b=0;
    for (int i =0;i<3600;i++)
    {
    a = d.nextInt(6) + 1;
    b = d.nextInt(6) + 1;
    switch(a+b)
    {
    case 2:
      nums[0]++;
      break;
    case 3:
      nums[1]++;
      break;
    case 4:
      nums[2]++;
      break;
    case 5:
      nums[3]++;
      break;
    case 6:
      nums[4]++;
      break;
    case 7:
      nums[5]++;
      break;
    case 8:
      nums[6]++;
      break;
    case 9:
      nums[7]++;
      break;
    case 10:
      nums[8]++;
      break;
    case 11:
      nums[9]++;
      break;
    case 12:
      nums[10]++;
      break;
    }

    }
    
    for (int i =0;i<11;i++)
      System.out.println(nums[i] + 
      " played that had the sum of " + (i+2));
  }
}

No comments:

Post a Comment