// DeMere1.java // This applet rolls a die in sets of four, seeing if a six comes up // in each one. // Written by Julian Devlin, 8/97, for the text book // "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell // Packages we need import java.awt.*; import java.applet.Applet; import java.util.Random; public class DeMere1 extends Applet { TextArea disp; // Area to display percentage Panel contp; // Panel for user controls Label numl; // Controls TextField num; Button go; JRandom myRand; // Random number generator // Initialize applet public void init() { numl = new Label("No. of games"); // Create controls num = new TextField("30", 4); go = new Button("Go"); contp = new Panel(); // Set up control panel contp.add(numl); contp.add(num); contp.add(go); contp.setLayout(new FlowLayout()); disp = new TextArea(10, 30); // Create display area setLayout(new FlowLayout()); add(disp); add(contp); validate(); myRand = new JRandom(); // Create random number generator } // Handle events public boolean handleEvent(Event evt) { if (evt.target instanceof Button) { if (evt.target == go && evt.id == Event.ACTION_EVENT) // When button is clicked { disp.setText(""); // Reset output window generate(Integer.valueOf(num.getText()).intValue()); return true; // Generate correct number of games } } return super.handleEvent(evt); // Handle other events as usual } // Generate n sets of 4 rolls, and print average wins (you get a six) public void generate(int n) { int count = 0; int randInt; float percent; for(int i = 0; i < n; i++) // Num of games { for(int j = 0; j < 4; j++) // Four rolls each game { randInt = myRand.nextInt(6); if (randInt == 6) // Check for a six { count++; j = 4; // Leave loop } } } percent = ((float) count/ (float) n) * 100; // Print results disp.appendText(Float.toString(percent)); disp.appendText("% win rate."); } }