package?org.java.exception;
/**
?*?圖書不存在異常
?*?@author?1
?*
?*/
public?class?BookNotNullException??extends?Exception{
public?BookNotNullException()?{
}
public?BookNotNullException(String?message)?{
super(message);
}
}
package?org.java.exception;
/**
?*?指令輸入錯誤異常;
?*?@author?1
?*
?*/
public?class?InstructNotException?extends?Exception{
public?InstructNotException()?{
}
public?InstructNotException(String?message)?{
????super(message);
}
}
package?org.java.exception;
import?java.util.Scanner;
public?class?BookTest?{
public?static?void?main(String[]?args){
String[]?str?=?{"語文","高數(shù)","英文","java","c","c++","jsp","PHP","Jquery","生物"};
Scanner?input?=?new?Scanner(System.in);
int?state=1;
System.out.println("歡迎進入圖書查詢系統(tǒng)>>>>>>>");
do{
System.out.println("請選擇查詢條件?1按索引查詢?2按書名查詢");
???try?{
?????????int?a?=?input.nextInt();
?????????if(a==1){//輸入為1時
?????????????System.out.println("輸入1-10進行查詢");
?????????????int?b?=?input.nextInt();
?????????try?{
?????????????if(b>0&&b<=10)?{
?????????????????System.out.println("book:"+str[b-1]);?
?????????????}else?{
?????????????????throw?new?BookNotNullException();
?????????}
????????}?catch?(BookNotNullException?e)?{
????????????System.out.println("圖書不存在異常");
????????}finally?{
????????????System.out.println("是否繼續(xù)查詢:1是?2否");
????????int?d?=?input.nextInt();
????????if(d==1)?{
????????state??=?1;?
????????}else?{
????????state?=0;
????????}
????}
?}else?if(a==2){//書名查詢時?不存在
?????????System.out.println("請輸入查詢的書名");
???????????String?book?=?input.next();
????????????try?{
??????????????int?c??=?findBookByName(book,str);
?????????????????if(c==0)?{
????????????????????????throw?new?BookNotNullException();?//拋出異常
?????????????????}
????????????????}?catch?(BookNotNullException?e)?{
????????????????????System.out.println("圖書不存在異常");
????????????????}finally?{
????????????????System.out.println("是否繼續(xù)查詢:1是?2否");
????????????????int?d?=?input.nextInt();
????????????????if(d==1)?{
????????????????state??=?1;?
????????????}else?{
????????state?=0;
????????}
}????
}else?{?
???throw?new?InstructNotException();//指令輸入錯誤異常
?????}
?????}?catch?(InstructNotException?e?)?{
?????????System.out.println("指令輸入錯誤異常");
????????????System.out.println("是否繼續(xù)查詢:1是?2否");
????????????int?d?=?input.nextInt();
????????if(d==1)?{
????????????state??=?1;?
????????}else?{
????????????state?=0;
????????}
????????}
}while(state!=0);
System.out.println("結束查詢");
}?
public?static?int?findBookByName(String?book,String[]?str)?{
for(int?i=0;i<str.length;i++)?{
?if(book.equals(str[i]))?{
?System.out.println("book:"+str[i]);
?return?1;
?}
?}??
return?0;
}
}
2018-10-14
?
throw
?new
?BookNotNullException();
請問拋這個異常的時候,不需要在方法頭進行聲明嗎?
2018-09-18
試一下把查詢條件寫成函數(shù)