/* * File: TestRandom.java * Author: Java, Java, Java * Description: This program tests the java.lang.Math.random() * method by simulating a six-faced die. The die is rolled * NTRIALS times ands its face value is tabulated in an array. * The number of rolls for each die is printed. If the random * number generator is relatively good, each die face should * come up approximately 1/6 of the time. * Math.random() returns a real number, r such that 0 <= r < 1 * Note the expression for scaling the random number to a * integer value between 1 and 6 (NFACES) * 1 + (int)(Math.random() * NFACES) */ public class TestRandom { public static final int NTRIALS = 6000; // Number of experimental trials private final int NFACES = 6; // Number of faces on the die private int counter[] = { 0,0,0,0,0,0 } ; // The six counters /** * testDie() rolls a NFACES die nTrials times * @param nTrials -- the number of die rolls * Pre: counter[] array has been initialized * and nTrials, the number of trials, is >= 0. * Post: the frequencies of nTrials die rolls will be recorded in counter[] */ public void testDie(int nTrials) { int die; // Represents the die for (int k = 0; k < nTrials; k++) { // For each trial die = 1 + (int)(Math.random() * NFACES); // Toss the die ++counter[die - 1]; // Update the appropriate counter } // for } //testDie() /** * printResults() display's the array's values * Pre: counter[] array has been initialized and nTrials >= 0 * Post: the value of each counter is printed */ public void printResults(int nTrials) { System.out.println("Out of " + nTrials + " die rolls, there were: "); for (int k = 1; k <= NFACES; k++) System.out.println(" " + counter[k-1] + " " + k + "s"); } // printResults() /** * main() creates an instance of TestRandom and conducts * the die rolling experiment. */ public static void main(String args[]) { TestRandom tester = new TestRandom(); tester.testDie(NTRIALS); tester.printResults(NTRIALS); } // main() } // TestRandom