// Quiz.java
// An applet to present randomly generated multiplication problems
// until the student gets them right.

import java.applet.Applet;   // import Applet class
import java.awt.*;           // import Label and TextField classes
import java.awt.event.*;     // import event handlers

public class Quiz extends Applet implements ActionListener{
  Label prompt;              // Question is output here.
  TextField input;           // student's answer is input here.
  int p,q;                   // numbers to multiply
  int answer;                // student's answer

  // Set up the graphical user interface.
  public void init ()
    {
      // Initialize the question field and put it on the quiz.
      prompt = new Label("A multiplication quiz, by Heidi Burgiel");
      add (prompt);

      // Create the answer field and put it on the quiz.
      input = new TextField(10);
      add (input);

      // Initialize something to notice and react when a new answer is input.
      // "this" refers to this applet 
      input.addActionListener (this);

      // Generate the initial question.
      newQuestion();
    }

  // Redraws the screen.
  public void paint (Graphics g)
    {
      // Ask the question.
      // Integer.toString turns numerical values into numerals.
      prompt.setText( "What is " + Integer.toString(p) + " x " + Integer.toString(q) + "?");

      // Clear answer field.
      input.setText("");
    }


  // Method to generate a new question.
  public void newQuestion ()
    {
      // Generates a random number from 0.0 to 1.0, then scales it
      // to be between 0.0 and 10.0, then "casts" it to an integer 
      // between 0 and 9.
      p = (int) (Math.random() * 10);
      q = (int) (Math.random() * 10);
    }      


  // Ask the question until the right answer is given.
  public void actionPerformed (ActionEvent e)
    {
      // Put the question on the screen.
      repaint();

      // Get the answer and convert it to an integer.
      answer = Integer.parseInt( e.getActionCommand());
      
      // Grade the problem; if the answer is correct change the question.
      if (p*q == answer){
	showStatus("Correct!");
	newQuestion();
      }
      else{
	showStatus("Nope!");
      }
    }
}
