package?kasei;
import?java.util.Scanner;
/**
?*?錯誤處理練習(xí)
?*?字符串?dāng)?shù)組保存圖書信息
?*?用戶通過書名和序號查找圖書
?*?輸入類型和值錯誤捕獲并返回
?*/
public?class?Book?{
????public?static?Scanner?input?=?new?Scanner(System.in);
????public?static?String[]?books?=?{"專心學(xué)習(xí)",?"提高?注意力",?"少摸魚","test"};
????public?static?void?main(String[]?args)?{
????????Book?book?=?new?Book();
????????book.initSearch();
????}
????/**
?????*?重頭開始輸入
?????*/
????public?void?initSearch()?{
????????Book?book?=?new?Book();
????????String?bookName?=?"";
????????try?{
????????????int?searchType?=?book.selectSearchType();
????????????switch?(searchType){
????????????????case?1:
????????????????????bookName?=?searchBookByName();
????????????????????break;
????????????????case?2:
????????????????????bookName?=?searchBookById();
????????????????????break;
????????????}
????????????System.out.println("book:?"+bookName);
????????}?catch?(SearchTypeException?e)?{
????????????System.out.println(e.message);
????????}?catch?(SearchBookException?e){
????????????System.out.println(e.message);
????????}?catch?(Exception?e){
????????????System.out.println("迷之錯誤");
????????}finally?{
????????????book.initSearch();
????????}
????}
????public?int?selectSearchType()?throws?SearchTypeException?{
????????System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
????????int?serchType?=?input.nextInt();
????????input.nextLine();?//?去掉隱藏的回車
????????if?(serchType?==?1?||?serchType?==?2)?{
????????????return?serchType;
????????}else{
????????????throw?new?SearchTypeException("命令輸入錯誤!請根據(jù)提示輸入數(shù)字命令!");
????????}
????}
????public?String?searchBookByName()?throws?SearchBookException?{
????????System.out.println("輸入圖書名稱:");
????????String?bookName?=?(String)input.nextLine();
????????for?(String?book?:?books)?{
????????????if?(bookName.equals(book))?{
????????????????return?bookName;
????????????}
????????}
????????throw?new?SearchBookException("圖書名稱不存在!");
????}
????public?String?searchBookById()?throws?SearchBookException{
????????System.out.println("輸入圖書序號:");
????????int?id?=?input.nextInt();
????????try?{
????????????String?bookName?=?books[id];
????????????return?bookName;
????????}catch?(Exception?e){
????????????throw?new?SearchBookException("圖書序號不存在!");
????????}
????}
}
package?kasei;
public?class?SearchBookException?extends?Exception?{
????public?String?message;
????public?SearchBookException(String?message){
????????super(message);
????????this.message?=?message;
????}
}
package?kasei;
public?class?SearchTypeException?extends?Exception?{
????public?String?message;
????public?SearchTypeException(String?message){
????????super(message);
????????this.message?=?message;
????}
}
2020-02-22
厲害,牛氣