package kasei;
import java.util.Scanner;
/**
* 错误处理练习
* 字符串数组保存图书信息
* 用户通过书名和序号查找图书
* 输入类型和值错误捕获并返回
*/
public class Book {
public static Scanner input = new Scanner(System.in);
public static String[] books = {"专心学习", "提高 注意力", "少摸鱼","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("命令输入错误!请根据提示输入数字命令!");
}
}
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;
}
}