/** * A class to test the "randomness" of a simulated die. */ public class DieTest { public static void main(String[] args) { int count1 = 0; // counts number of 1s rolled int count2 = 0; // counts number of 2s rolled int count3 = 0; // counts number of 3s rolled int count4 = 0; // counts number of 4s rolled int count5 = 0; // counts number of 5s rolled int count6 = 0; // counts number of 6s rolled N_SidedDie myDie = new N_SidedDie(6); // creates a 6-sided die final int NUMBER_OF_TRIALS = 100 ; // number of test rolls to do // roll the die "numberOfTrials" times and count the frequency // of each outcome int times = 1; // counts number of rolls while (times <= NUMBER_OF_TRIALS) // while more rolls to be done... { int test = myDie.roll(); // roll the die // increment the counter for the number rolled switch(test) { case 1: count1++ ; break ; case 2: count2++ ; break ; case 3: count3++ ; break ; case 4: count4++ ; break ; case 5: count5++ ; break ; case 6: count6++ ; break ; default: // an error has occurred System.out.println("*** BAD DIE ***\nNUMBER ROLLED: " + test); System.exit(1); // end program! } times++ ; } // report the percentage of rolls for each outcome 1..6 double divisor = (double)NUMBER_OF_TRIALS ; // to avoid integer division in switch, below times = 1; // LCV while (times <= 6) // repeat 6 times - once for each outcome { double percent = 0.0; switch(times) { case 1: percent = (count1 / divisor) * 100 ; break ; case 2: percent = (count2 / divisor) * 100 ; break ; case 3: percent = (count3 / divisor) * 100 ; break ; case 4: percent = (count4 / divisor) * 100 ; break ; case 5: percent = (count5 / divisor) * 100 ; break ; case 6: percent = (count6 / divisor) * 100 ; } System.out.printf("%d : %.2f", times, percent) ; System.out.println("%") ; } } }