dividebyzerotest.java

来自「非常好的java原程序学习」· Java 代码 · 共 74 行

JAVA
74
字号
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;   }}public class DivideByZeroException extends ArithmeticException {   public DivideByZeroException()   {      super( "Attempted to divide by zero" );   }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?