第五次實訓
阿新 • • 發佈:2019-05-13
計算 不能 int() 實訓 鍵盤輸入 pub package main方法 ner
/*. 編寫一個類ExceptionTest, 在main方法中使用try-catch-finally語句結構實現: ² 在try語句塊中,編寫兩個數相除操作,相除的兩個操作數要求程序運行時用戶輸入; ² 在catch語句塊中,捕獲被0除所產生的異常,並輸出異常信息; ² 在finally語句塊中,輸出一條語句。*/ package 第五次實訓; import java.util.Scanner; public class ExceptionText { public static void main(String[] args) {try { int x,y; System.out.println("請輸入需要相除的兩個數:"); Scanner reader =new Scanner(System.in); x=reader.nextInt(); y=reader.nextInt(); System.out.println("兩個數相除結果為:"+x/y); } catch(ArithmeticException e){ System.out.println("除數不能為0"); } finally { System.out.println("over"); } } }
/*編寫一個應用程序,要求從鍵盤輸入一個double型的圓的半徑,計算並輸出其面積。 * 測試當輸入的數據不是double型數據(如字符串“abc”)會產生什麽結果,怎樣處理。 */ package 第五次實訓; import java.util.Scanner; public class QWQ { public static voidmain(String[] args) { double r; final double PI=3.14; try { System.out.println("請輸入該圓的半徑:"); Scanner reader=new Scanner(System.in); r=reader.nextDouble(); System.out.println("該圓的面積是:"+r*r*PI); } catch(Exception e) { System.out.println("錯誤!"); } finally { System.out.println("over"); } } }
/*為類的屬性“身份證號碼.id”設置值,當給的的值長度為18時,賦值給id,當值長度不是18時, * 拋出IllegalArgumentException異常,然後捕獲和處理異常,編寫程序實現以上功能。 */ package 第五次實訓; import java.util.Scanner; public class QAQ { static String ID; static void ID(int lenght)throws Exception{ if(ID.length()!=18) { throw new Exception("請輸入18位有效數學!"); } } public static void main(String[] args) { Scanner reader =new Scanner(System.in); ID=reader.next(); try { ID.length(); System.out.println("身份證號碼為:"); } catch(Exception e){ System.out.println("錯誤!請輸入18位有效數字!"); } finally { System.out.println("over"); } } }
心得體會:
對於自定義異常,拋出異常不是很理解,按照書上生搬硬套有點難受,下次追求進步
第五次實訓