// Helene Martin, CSE 142 // Demonstrates usage of the Random class. // Simulates dice rolls (I got excited so I had to code it up. Expected value!). import java.util.*; public class RandomDemo { public static final int SIMULATION_COUNT = 100000; public static void main(String[] args) { Random rand = new Random(); // A random number between 1 and 47 inclusive? int num1 = rand.nextInt(47) + 1; /* Add 1 to shift the range by 1. Example: rand.nextInt(3) +1 0 -> 1 1 -> 2 2 -> 3 */ // A random number between 23 and 30 inclusive? // Number of different choices: max - min + 1 // to generate a number in the range [min, max]: // rand.nextInt(number of choices) + min; int num2 = rand.nextInt(8) + 23; // A random even number between 4 and 12 inclusive? int num3 = (rand.nextInt(5) + 2) * 2; int triesUntil7 = diceRolls(rand); System.out.println("You got it in " + triesUntil7 + " times"); int totalTries = 0; int runs = 0; for (int i = 0; i < SIMULATION_COUNT; i++) { totalTries += diceRolls(rand); runs++; } System.out.println("Average tries after " + SIMULATION_COUNT + " runs: " + (double)totalTries / runs); } // Simulates rolling two dice until their sum is 7. // Returns the number of rolls that takes. public static int diceRolls(Random rand) { int times = 0; int sum = -1; while (sum != 7) { int die1 = rand.nextInt(6) + 1; int die2 = rand.nextInt(6) + 1; times++; sum = die1 + die2; // commented out for 100,000 runs //System.out.println(die1 + " + " + die2 + " = " + sum); } return times; } }