// HTLead.java // Written by Julian Devlin, 8/97, for the text book // "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell import java.applet.Applet; import java.awt.*; public class HTLead extends java.applet.Applet { Float[] yCoords; // Variables for simulation Float[] xCoords; SpikeGraph sg; // AWT elements Label message; Label message2; Button go; TextField numFlips; TextField numGames; Panel graphArea; Panel controls; // Set up all controls and put them in the window public void init() { message = new Label("tosses per game ="); // Create controls message2 = new Label("number of games ="); go = new Button("Simulate"); numFlips = new TextField(3); numGames = new TextField(4); graphArea = new Panel(); // Set up window controls = new Panel(); setLayout(new BorderLayout()); controls.setLayout(new FlowLayout()); controls.add(message); controls.add(numFlips); controls.add(message2); controls.add(numGames); controls.add(go); sg = new SpikeGraph(); // initialize a graphing space add("Center", sg); add("South", controls); } // Does the simulation, creating two arrays to store game states, then passes them // to a SpikeGraph public void simulate() { int yCoord; // Running count of game score int prevY; int inLead; int nf = 0; try { nf = Integer.parseInt(numFlips.getText().trim()); // Get user input } catch (Exception e) { numFlips.setText(""); validate(); } int ng = 0; try { ng = Integer.parseInt(numGames.getText().trim()); // Get user input } catch (Exception e) { numGames.setText(""); validate(); } xCoords = new Float[nf + 1]; // Make arrays yCoords = new Float[nf + 1]; for (int i = 0; i < nf + 1; i++) { xCoords[i] = new Float(i); yCoords[i] = new Float(0); } for (int i = 0; i < ng; i++) { // Do actual simulation yCoord = 0; inLead = 0; for (int j = 0; j < nf; j++) { // BETTER INITIALIZATION prevY = yCoord; if (Math.random() < 0.5) yCoord++; else yCoord--; if (yCoord > 0) inLead++; else if (yCoord == 0) if (prevY > 0) inLead++; } int temp = yCoords[inLead].intValue(); yCoords[inLead] = new Float(temp + 1); } remove(sg); sg = new SpikeGraph(xCoords, yCoords); // Create new SpikeGraph add("Center", sg); // Put up the graph validate(); } // Watch for a click on the go button public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) { if ((String)arg == "Simulate") { simulate(); } } return true; } public Insets insets() { return new Insets(5,5,5,5); } }