// Die.java // Purpose: Simulates rolling a six-sided die x number of times // Author: Mark Spurlock // Date: October 29, 1996 (CS594 Lab 6) // Get needed class libraries import java.awt.*; import java.applet.Applet; import java.util.Random; public class Die extends Applet { Label prompt; TextField input; int number; int face; int frequency[]; Random r; public void init() { // Setup the GUI components and initialize variables prompt = new Label("Input times to roll die and press Enter:"); input = new TextField(10); frequency = new int[7]; number = 0; add(prompt); add(input); } public void paint(Graphics g) { // Put die data on screen int yPosition; yPosition = 75; g.drawString("Face", 25, yPosition); g.drawString("Frequency", 100, yPosition); for (face = 1; face < frequency.length; face++) { yPosition += 15; g.drawString(String.valueOf(face), 25, yPosition); g.drawString(String.valueOf(frequency[face]), 100, yPosition); frequency[face] = 0; } input.setText(""); } public boolean action(Event event, Object o) { // Process user's action and roll die if (event.target == input) { // User pressed return inside input field number = Integer.parseInt(input.getText()); r = new Random(); for (int roll = 1; roll <= number; roll++) { // Add one to appropriate array entry face = 1 + Math.abs(r.nextInt() % 6); ++frequency[face]; } repaint(); // Post new data } return true; } }