// Fig. 12.1: DivideByZeroTest.java
// A simple exception handling example.
// Checking for a divide-by-zero-error.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

public class DivideByZeroTest extends Applet
             implements ActionListener {
   private Label prompt1, prompt2;
   private TextField input1, input2;
   private int number1, number2;
   private double result;

   // Initialization
   public void init()
   {
      prompt1 = new Label( "Enter numerator" );
      add( prompt1 );

      input1 = new TextField( 10 );
      add( input1 );

      prompt2 =
         new Label( "Enter denominator and press Enter" );
      add( prompt2 );

      input2 = new TextField( 10 );
      input2.addActionListener( this );
      add( input2 );
   }

   // Process GUI events
   public void actionPerformed( ActionEvent e )
   {
      DecimalFormat precision3 = new DecimalFormat( "#.000" );

      try {
         number1 = Integer.parseInt( input1.getText() );
         number2 = Integer.parseInt( input2.getText() );
         input1.setText( "" );
         input2.setText( "" );

         result = quotient( number1, number2 );
         showStatus( number1 + " / " + number2 + " = " +
                     precision3.format( result ) );
      }
      catch ( NumberFormatException nfe ) {
         showStatus( "You must enter two integers" );
      }
      catch ( DivideByZeroException dbze ) {
         showStatus( dbze.toString() );
      }
   }

   // Definition of method quotient. Used to demonstrate
   // throwing an exception when a divide-by-zero error
   // is encountered.
   public double quotient( int numerator, int denominator )
      throws DivideByZeroException
   {
      if ( denominator == 0 )
         throw new DivideByZeroException();

      return ( double ) numerator / denominator;
   }
}


