我想問(wèn)一下,輸入錯(cuò)誤之后怎樣才能讓用戶重新輸入呢?
package?com.jersey; import?java.util.*; import?javax.sql.rowset.spi.SyncFactoryException; public?class?LibSystem?{ static?Book[]?books={new?Book("論語(yǔ)","000001"),new?Book("老子","000002"),new?Book("java編程思想","000003")}; public?static?void?main(String[]?args){ System.out.println("歡迎來(lái)到iLibrary圖書(shū)檢索系統(tǒng)!"); Scanner?input=new?Scanner(System.in); System.out.println("請(qǐng)選擇:1.按書(shū)名檢索?2.按編號(hào)檢索?3.退出系統(tǒng)"); int?n=input.nextInt(); switch(n){ case?1: System.out.println("請(qǐng)輸入您所要檢索的圖書(shū)名稱"); String?a=input.next(); try{ String?result=SearchByName(a); System.out.println("您所選的《"+result+"》已找到"); }catch(Exception?e){ e.printStackTrace(); System.out.println("您檢索的圖書(shū)不存在!"); } break; case?2: System.out.println("請(qǐng)輸入您所要檢索的圖書(shū)編碼"); String?b=input.next(); try{ String?result2=SearchByCode(b); System.out.println("您所選的《"+result2+"》已找到"); }catch(Exception?e){ e.printStackTrace(); System.out.println("您輸入的編碼有誤,請(qǐng)重新輸入!"); } break; case?3: System.exit(0); default: System.out.println("您的輸入有誤!請(qǐng)重新輸入!"); } } public?static?String?SearchByName(String?a)?throws?Exception{ for(int?i=0;i<books.length;i++){ if(a.equals(books[i].name)){ continue; } else{ throw?new?Exception(); } } return?a; } public?static?String?SearchByCode(String?b)?throws?Exception{ String?s2=b; for(int?i=0;i<books.length;i++){ if(b.equals(books[i].code)){ s2=books[i].name; break; } else{ throw?new?Exception(); } } return?s2; } }
諸位還有什么改進(jìn)的建議也請(qǐng)告訴我,謝謝!
2015-08-12
我這沒(méi)有Book類,模擬一下吧
2015-08-26
示例代碼中的異常處理也有問(wèn)題啊,壓根不能判斷輸入的信息是否與已有數(shù)據(jù)相匹配,而且真心不明白這里的兩個(gè)異常處理有什么作用!
2015-08-24
也可以嘗試一下
boolean ?retry=true;
? ? ? ? ? ? ? ? ?while(needretry){
? ? ? ? ? ? ? ? ? try{
????????????????????????????????//執(zhí)行的代碼塊1
????????????????????????????????retry=false;//沒(méi)有錯(cuò)誤不需要重來(lái)
? ? ? ? ? ? ? ? ? ? ? }catch(Exception e){
????????????????????????????????????//執(zhí)行代碼塊2
????????????????????????????????????? retry=true;//有錯(cuò)誤,要重來(lái) ?
????????????????????????????????????????????}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
這個(gè)模板只是大概的,你可以根據(jù)需要添加其他條件語(yǔ)句及判斷。
親測(cè)有效