package?library;
import?java.util.Scanner;
public?class?BorrowBook?{
public?static?void?main(String[]?args)?{
int?choose;
try{System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
@SuppressWarnings("resource")
Scanner?input?=?new?Scanner(System.in);
choose?=?input.nextInt();
if(choose!=1&&choose!=2)
throw?new?Exception();
}catch(Exception?e){
System.out.println("命令輸入錯誤!請根據(jù)提示輸入數(shù)字命令!");
System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
@SuppressWarnings("resource")
Scanner?input?=?new?Scanner(System.in);
choose?=?input.nextInt();
}
if(choose==1){
System.out.println("請輸入圖書名稱:");
@SuppressWarnings("resource")
Scanner?input?=?new?Scanner(System.in);
String?bookName?=?input.nextLine();
NameFind?find?=?new?NameFind();
try?{
find.find(bookName);
}?catch(NameException?e){
e.printStackTrace();
}
catch?(Exception?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}//if(choose==1)
?????if(choose==2){
???? ?System.out.println("請輸入圖書序號:");
???? ?@SuppressWarnings("resource")
Scanner?input2?=?new?Scanner(System.in);
???? ?int?bookNum?=?input2.nextInt();
???? ?NumFind?find2?=?new?NumFind();
???? ?try?{
find2.find(bookNum);
}?catch?(NameException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}catch?(Exception?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
?????}//if(choose2)
}//main
}//class
package?library;
public?class?NameFind?{
String[]?name?=?{"高數(shù)","數(shù)據(jù)結(jié)構(gòu)"};
public?void?find?(String?book)throws?NameException?{
int?count=0;
for(int?i=0;i<name.length;i++)
if(book.equals(name[i]))
System.out.println("book:"+name[i]);
else?count++;
if(count==name.length&&(!name[count].equals(book)))
????throw?new?NameException("圖書不存在");
??}//find
}//class
package?library;
public?class?NumFind?{
String[]?name?=?{"高數(shù)","數(shù)據(jù)結(jié)構(gòu)"};
int[]?num?=?{1,2};
int?count?=??0;
public?void?find(int?book)throws?NameException{
for(int?i=0;i<num.length;i++)
if(book==num[i]){
System.out.println("book:"+name[i]);
}else{
count++;
}
if(count==name.length&&(num[count]!=book))
?throw?new?NameException("圖書不存在");
???????}
}
package?library;
public?class?NameException?extends?Exception{
public?NameException(){
System.out.println("圖書不存在");
}
public?NameException(String?msg){
super(msg);
}
}
2015-10-26
異常的位置處理方式有錯誤,算法錯誤
2015-07-27
這樣的可以嗎?可以我就把源代碼給你。
2015-07-27
我輸出的有異常信息,不知道是不是你想要的