使用例外處理

import java.util.InputMismatchException;
import java.util.Scanner;
public class DivideByZero
{
    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("請輸入被除數:");
          int numerator = scanner.nextInt();
          System.out.print("請輸入除數:");
          int denominator = scanner.nextInt();
         
          int result = quotient ( numerator, denominator );
          System.out.printf("\n答案:%d / %d = %d\n" , numerator, denominator, result);
          continueLoop = false;
          
          }
          
          catch ( InputMismatchException inputMismatchException )
          {
             System.err.printf("\nException:%s\n", inputMismatchException);
             scanner.nextLine();
             System.out.println("你必須輸入整數,請再試一次。\n");
          }
          catch ( ArithmeticException arithmeticException )
          {
             System.err.printf("\nException:%s\n", arithmeticException);
             System.out.println("發生除以0的錯誤,請再試一次。\n");
          }
       }while ( continueLoop );
    }
}
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 a25561970 的頭像
    a25561970

    萬花筒

    a25561970 發表在 痞客邦 留言(0) 人氣()