//////////////////////////////////////////////////////////// // // Whizzo Number Guesser Applet // // LIS533 Spring 1998 // // Illustrates text boxes, user input and // some calculations // //////////////////////////////////////////////////////////// import java.applet.*; import java.awt.*; import java.util.Random; public class rndom extends Applet { Roulette r = new Roulette(); Panel p, q; Label question, prompt, result; TextField t, t2, t3; Button b; public void init() { /////////////////////////////////////// // // set layout setLayout(new BorderLayout()); /////////////////////////////////////// // // Panels to hold buttons, textfields, etc. p = new Panel(); setBackground(Color.red); Label herald = new Label("Whizzo Number Guesser", Label.CENTER); p.add(herald); add("North",p); q = new Panel(); q.setBackground(Color.yellow); GridBagLayout g = new GridBagLayout(); q.setLayout(g); GridBagConstraints c1 = new GridBagConstraints(); c1.fill = GridBagConstraints.BOTH; c1.gridwidth = GridBagConstraints.REMAINDER; c1.gridx = -1; c1.gridy = -1; question = new Label("Enter a number 0 .. 9",Label.CENTER); g.setConstraints(question, c1); q.add(question); c1.gridwidth = GridBagConstraints.RELATIVE; c1.gridx = 1; c1.gridy = 1; prompt = new Label("Your number: ",Label.RIGHT); g.setConstraints(prompt, c1); q.add(prompt); c1.gridwidth = GridBagConstraints.REMAINDER; c1.gridx = 3; c1.gridy = 1; t = new TextField("?", 5); g.setConstraints(t, c1); q.add(t); c1.gridwidth = GridBagConstraints.RELATIVE; c1.gridx = 1; c1.gridy = 2; b = new Button("Make Whizzo Guess"); g.setConstraints(b, c1); q.add(b); c1.gridwidth = GridBagConstraints.REMAINDER; c1.gridx = 3; c1.gridy = 2; t2 = new TextField("?",5); g.setConstraints(t2, c1); q.add(t2); c1.gridwidth = GridBagConstraints.RELATIVE; c1.gridx = 1; c1.gridy = 3; result = new Label("Difference is : ", Label.RIGHT); g.setConstraints(result, c1); q.add(result); c1.gridwidth = GridBagConstraints.REMAINDER; c1.gridx = 3; c1.gridy = 3; t3 = new TextField("?",5); g.setConstraints(t3, c1); q.add(t3); add("Center",q); }// init public boolean action(Event e, Object arg) { int iUserInput, result; if ("Make Whizzo Guess".equals(arg)) { /////////////////////////////////////////// // Produce a random number for textfield t2 t2.setText(r.spin()); //////////////////////////////////////////// // Read user input; change to integer iUserInput = Integer.parseInt(t.getText()); //////////////////////////////////////////// // Compare to integer produced by Roulette object r result = iUserInput - r.num; //////////////////////////////////////////// // Set the absolute value in textfield t3 t3.setText(String.valueOf(Math.abs(result))); return true; } return false; } // action } // rndom class Roulette { Random generator = new Random(); int rand, num; String spin() { rand = generator.nextInt(); num = Math.abs(rand % 10); return(Integer.toString(num)); }// spin } // Roulette