/*********************************************************** 示範method中直接丟出例外,由另外的class接收處理 ***********************************************************/ import java.io.*; class fra{ int fraction(int y) throws ArithmeticException { int i,ans; if (y<0) throw new ArithmeticException(); //丟出例外 ans=1; for (i=1;i<=y;i=i+1) { ans=ans*i; } // for 結束 return(ans); } // fraction 結束 } public class demo28a{ public static void main(String args[]) { //程式進入點 String getbr; BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); fra fr=new fra(); //弄另外一個class來計算階乘 int x; /*****請使用者輸入選項**********/ x=5; while (x>0) { System.out.print("請輸入要計算階乘的數字(輸入0結束):"); try { getbr = br.readLine(); x=Integer.parseInt(getbr); } catch(NumberFormatException e){ //處理輸入文字 System.out.println("請不要亂輸入好嗎?我要的是數字ㄟ!"); x=100; //讓while繼續跑 continue; } catch(IOException e){//處理鍵盤遇到錯誤 System.out.println("程式停止,謝謝使用!"); return; } if (x==0) { System.out.println("謝謝!再見!"); continue; } try{ System.out.println(x+ "!="+fr.fraction(x)); } catch(ArithmeticException e) { System.out.println("老大!輸入正整數好嗎?"); x=100; //讓while繼續跑 continue; } } //while結束 } //main 結束 }