集册 Java实例教程 处理ArithmeticException和InputMismatchException。

处理ArithmeticException和InputMismatchException。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

517
处理ArithmeticException和InputMismatchException。

import java.util.InputMismatchException;

import java.util.Scanner;
/*from N o w J a v a . c o m - 时代Java*/

public class Main

{

   // demonstrates throwing an exception when a divide-by-zero occurs

   public static int quotient(int numerator, int denominator)

      throws ArithmeticException

   {

      return numerator / denominator; // possible division by zero

   } 


   public static void main(String[] args)

   {

      Scanner scanner = new Scanner(System.in); 
      /*
      来 自*
       N o w J a v a . c o m - 时代Java
      */

      boolean continueLoop = true; // determines if more input is needed


      do

      {

         try // read two numbers and calculate quotient

         {

            System.out.print("Please enter an integer numerator: ");

            int numerator = scanner.nextInt();

            System.out.print("Please enter an integer denominator: ");

            int denominator = scanner.nextInt();


            int result = quotient(numerator, denominator);

            System.out.printf("%nResult: %d / %d = %d%n", numerator,

               denominator, result);

            continueLoop = false; // input successful; end looping

         }

         catch (InputMismatchException inputMismatchException)

         {

            System.err.printf("%nException: %s%n",

               inputMismatchException);

            scanner.nextLine(); // discard input so user can try again

            System.out.printf(

               
展开阅读全文