16-random-number-examples

16-random-number-examples - Mehran Sahami CS 106A Handout...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Handout #16 CS 106A October 7, 2009 Examples of Programs Using Random Numbers Portions of this handout by Eric Roberts /* * File: RollDice.java * ------------------- * This program simulates rolling some number of dice until * the maximal value on the all the dice is rolled. */ import acm.program.*; import acm.util.*; public class RollDice extends ConsoleProgram { /* Number of sides on each die */ private static final int NUM_SIDES = 6; public void run() { int numDice = readInt("Number of dice: "); int maxRoll = numDice * NUM_SIDES; int numRolls = 0; while (true) { int roll = rollDice(numDice); numRolls++; if (roll == maxRoll) break; println("Rolled " + roll); } println("Rolled " + maxRoll + " after " + numRolls + " rolls"); } /* Returns the total of rolling numDice dice */ private int rollDice(int numDice) { int total = 0; for (int i = 0; i < numDice; i++) { total += rgen.nextInt(1, NUM_SIDES); } return total; } /* Private instance variables */ private RandomGenerator rgen = RandomGenerator.getInstance();
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

16-random-number-examples - Mehran Sahami CS 106A Handout...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online