//需要對(duì)應(yīng)定義三個(gè)異常類(lèi),寫(xiě)的很差,好在是寫(xiě)出來(lái)了?只為自己紀(jì)念。
package?com.guoke;
import?java.util.Scanner;
import?java.util.InputMismatchException;
public?class?SimulatedLibrarySystem?{
private String?[]??books={"高數(shù)","數(shù)據(jù)結(jié)構(gòu)","慕課","123"};//圖書(shū)館的書(shū).不能放到main方法里面,因?yàn)榉胚M(jìn)去就是局部變量。
???public?static?void?main(String[]?args)?{
???System.out.println("輸入命令:1-按照名稱(chēng)查找圖書(shū);\t2-按照序號(hào)查找圖書(shū)");
????Scanner?scan=new?Scanner(System.in);//創(chuàng)建接收輸入對(duì)象scan
????SimulatedLibrarySystem?s=new?SimulatedLibrarySystem();//創(chuàng)建一個(gè)對(duì)象s,便于調(diào)用數(shù)組
????int?a=3;
????while((a!=1)&&(a!=2)){//輸入命令選擇查找方式
???? try{
???? ?a=scan.nextInt();//將輸入放入a中
???? s.getRightOrder(a);//判斷輸入是否正確,如無(wú)異常,則繼續(xù);
//??? ?System.out.println(b);
????}catch(InputMismatchException?e){//輸入的不是整型數(shù)字,捕獲異常
???? System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入命令字符!");
???? scan.next();//獲取Scanner對(duì)象掃描到的鍵盤(pán)輸入,如果不獲取,會(huì)因?yàn)閣hile一直給異常提示
????}catch(OrderNotExist?f){//輸入的不是1或2,捕獲異常
????
????}
????}
????switch(a){//進(jìn)入對(duì)應(yīng)的查找方式
????case?1:?while(a!=3){//進(jìn)入方式1
???? System.out.println("輸入圖書(shū)名稱(chēng)");
????????????try?{
???????????? String?book=scan.next();
???????????? book=s.getRightBook(book);//判斷圖書(shū)存在與否
???????????? System.out.println("book:"+book);
???????????????
}?catch?(BookNotExist?e)?{
//?TODO:?handle?exception
}
???????}
????case?2:??while(a!=3){//進(jìn)入方式2?輸入序號(hào)(數(shù)組下標(biāo))找書(shū)
???? System.out.println("輸入圖書(shū)序號(hào)");
???? try?{
???? int?number=scan.nextInt();//輸入下標(biāo)
???????? number=s.getRightBook2(number);//判斷圖書(shū)存在與否
???????? System.out.println("book:"+s.books[number]);
}?catch?(BookNotExist2?e)?{
//?TODO:?handle?exception
}
????}
//????System.out.println("over");
???}
???}
private??void??getRightOrder(int?a)?throws?OrderNotExist{//判斷輸入是否為1或2,否則拋出異常
if((a!=1)&&(a!=2)){
throw?new?OrderNotExist();
}
}
public??String?getRightBook(String?book)?throws?BookNotExist{//按書(shū)名找圖書(shū)
for(int?i=0;i<books.length;i++){
??if(book.equals(books[i])){//找到則返回圖書(shū)名
??return?book;
??}
}throw?new?BookNotExist();
}
public??int?getRightBook2(int?number)?throws?BookNotExist2{//按下標(biāo)找圖書(shū),找到則返回圖書(shū)名?否則報(bào)錯(cuò)
??if(number>books.length-1||number<0){//下標(biāo)超出數(shù)組范圍拋出異常
??throw?new?BookNotExist2();
??}
return?number;
}
}
2015-12-17
棒棒的。
看完視頻推薦來(lái)看你、
太有緣了