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

时间:2024-01-18 16:25:50
 //一段优美的例子
import java.util.Scanner;
import java.util.InputMismatchException; public class DevideByZeroWithoutNoException1{
public static int quotient(int numerator,int denominator)
throws ArithmeticException
{
return numerator/denominator;
} public static void main(String[] args) {
Scanner scanner=new Scanner(System.in); boolean continueLoop=true; do {
try
{
System.out.print("please enter an int numerator:");
int numerator=scanner.nextInt(); System.out.print("please enter an in denominator:");
int denominator=scanner.nextInt(); int result=quotient(numerator,denominator); System.out.printf("%nResult:%d/%d=%d%n",numerator,denominator,result); continueLoop=false; } catch (InputMismatchException inputMismatchException)
{
System.err.printf("%nException:%s%n",inputMismatchException);
scanner.nextLine();
System.out.printf("%nYou must enter an integer number.Please try again.%n%n");
} catch (ArithmeticException arithmeticException)
{
System.err.printf("%nException:%n%s",arithmeticException);
System.out.printf("%nZero is an invalid denom inator!Please try again.%n%n");
} } while (continueLoop); }
}