[20160701]DevideByZeroWithoutNoException——from 《Java How To Program (Early Objects), 10th》

 1 //一段优美的例子
 2 import java.util.Scanner;
 3 import java.util.InputMismatchException;
 4 
 5 public class DevideByZeroWithoutNoException1{
 6   public static int quotient(int numerator,int denominator)
 7     throws ArithmeticException
 8   {
 9     return numerator/denominator;
10   }
11 
12   public static void main(String[] args) {
13     Scanner scanner=new Scanner(System.in);
14 
15     boolean continueLoop=true;
16 
17     do {
18      try
19      {
20        System.out.print("please enter an int numerator:");
21        int  numerator=scanner.nextInt();
22 
23        System.out.print("please enter an in denominator:");
24        int  denominator=scanner.nextInt();
25 
26        int result=quotient(numerator,denominator);
27 
28        System.out.printf("%nResult:%d/%d=%d%n",numerator,denominator,result);
29 
30        continueLoop=false;
31 
32      }
33 
34     catch (InputMismatchException inputMismatchException)
35     {
36        System.err.printf("%nException:%s%n",inputMismatchException);
37        scanner.nextLine();
38        System.out.printf("%nYou must enter an integer number.Please try again.%n%n");
39     }
40 
41     catch (ArithmeticException arithmeticException)
42     {
43       System.err.printf("%nException:%n%s",arithmeticException);
44       System.out.printf("%nZero is an invalid denom inator!Please try again.%n%n");
45     }
46 
47 
48   } while (continueLoop);
49 
50 
51   }
52 }
原文地址:https://www.cnblogs.com/jasonzeng888/p/5632420.html