/** Dice.java - Let's simulate some dice rolls. Let the user specify the * number of dice, the desired sum, and how many trials. The results can * be used to compute empirical probability. Here are some examples we can * check. Rolling a sum of 11 with 3 dice should be 0.125. Rolling a sum * of 19 with 5 dice should be about 0.0945. * * The purpose of the program is to illustrate if statments and loops in * Java. We also do a little error checking of the input. We give up if * the input is invalid. */ public class Dice { public static void main(String [] args) { if (args.length != 3) { System.out.println("You need to supply three inputs: " + " "); System.exit(1); } int numDice = Integer.parseInt(args[0]); int desiredSum = Integer.parseInt(args[1]); int numTrials = Integer.parseInt(args[2]); if (numDice <= 0 || desiredSum <= 0 || numTrials <= 0) { System.out.println("All inputs must be positive."); System.exit(1); } // Now that we know we have good input, let the experiment begin! // Let's count how many times the desired sum occurs. int count = 0; for (int i = 0; i < numTrials; ++i) { int sum = 0; for (int j = 0; j < numDice; ++j) { int roll = (int)(Math.random() * 6) + 1; sum += roll; } if (sum == desiredSum) ++count; } // Output double prob = 1.0 * count / numTrials; System.out.println("" + count + " out of " + numTrials + " yielded a sum of " + desiredSum + ". Probability = " + prob); } }