public?class?Borrow?{
????public?static?void?main(String[]?args)?throws?CommandException,?NoResultException?{
????????Borrow?borrow?=?new?Borrow();
????????borrow.select();
????}
????public?void?select()?throws?CommandException,?NoResultException?{
????????String[]?books?=?{"西游記",?"紅樓夢",?"水滸傳",?"三國演義"};
????????Scanner?input?=?new?Scanner(System.in);
????????try?{
????????????System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
????????????int?ipt1?=?input.nextInt();
????????????if?(ipt1?==?1)?{
????????????????System.out.println("輸入圖書名稱:");
????????????????String?ipt2?=?input.next();
????????????????String?result?=?"";
????????????????for?(String?book?:?books)?{
????????????????????if?(ipt2.contentEquals(book))?{
????????????????????????result?=?book;
????????????????????}
????????????????}
????????????????if?(result?!=?"")?{
????????????????????System.out.println("book:"?+?result);
????????????????}?else?{
????????????????????throw?new?NoResultException("圖書不存在!");
????????????????}
????????????}?else?if?(ipt1?==?2)?{
????????????????System.out.println("輸入圖書序號:");
????????????????int?ipt3?=?input.nextInt();
????????????????if?(ipt3?>?books.length?||?ipt3?<=?0)?{
????????????????????throw?new?NoResultException("圖書不存在!");
????????????????}?else?if?(ipt3?>?0?&&?ipt3?<=?books.length)?{
????????????????????System.out.println("book:"?+?books[ipt3?-?1]);
????????????????}?else?{
????????????????????throw?new?CommandException("命令輸入錯誤!請根據提示輸入數字命令!");
????????????????}
????????????}?else?{
????????????????throw?new?CommandException("命令輸入錯誤!請根據提示輸入數字命令!");
????????????}
????????}?catch?(CommandException?e)?{
????????????System.out.println(e.getMessage());
????????????select();
????????}?catch?(NoResultException?e)?{
????????????System.out.println(e.getMessage());
????????????select();
????????}?catch?(InputMismatchException?e)?{
????????????System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
????????????select();
????????}
????}
}
public?class?CommandException?extends?Exception?{
????public?CommandException()?{ }
????public?CommandException(String?e)?{
????????super(e);
????}
}
public?class?NoResultException?extends?Exception?{
????public?NoResultException()?{?}
????public?NoResultException(String?e)?{
????????super(e);
????}
}
2019-04-01
1.你在主方法里聲明拋出異常,就是JVM來處理異常了,寫不寫都是一樣,出現異常都會報錯。
2.這個問題無關緊要,就是select方法里沒有聲明會拋出InputMismatchException異常
3.怎么連把代碼連同格式一起粘貼上去?我知道可以選代碼語言,但是選擇Java后我復制的代碼不會自動換行,只能我自己手動一行一行按回車換行。
2019-03-24
稍作調整可以正常運行