交作業了!??!
package exception_demo;
import java.util.Scanner;
public class Book {
public static void main(String[] args) {
// TODO Auto-generated method stub
Book bookObj = new Book();
bookObj.init();
}
public void init() {
String[] books = {"java","php","python","go"};
int type;
String BookName;
try {
type = searchType();
if(type == 1) {
BookName = searchBookName(books);
}else {
BookName = searchBookNum(books);
}
System.out.println("book:"+BookName);
}catch(BookException e) {
System.out.println(e.getMessage());
init();
}catch(Exception e) {
System.out.println(e.getMessage());
init();
}
}
//通過哪種類型選擇圖書
public int searchType() throws BookException {
Scanner input = new Scanner(System.in);//創建scanner對象
System.out.print("請輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
int type = input.nextInt();
if(type == 1 || type == 2) {
return type;
}else{
throw new BookException("命令輸入錯誤!請根據提示輸入數字命令!");
}
}
//通過名稱查找
public String searchBookName(String[] books) throws Exception {
Scanner input = new Scanner(System.in);//創建scanner對象
System.out.println("請輸入圖書名稱:");
String BookName = input.next();
for(String book :? books) {
if(book.equals(BookName)) {
return BookName;
}
}
throw new Exception("圖書不存在!");
}
//通過序號查找
public String searchBookNum(String[] books) throws Exception {
Scanner input = new Scanner(System.in);//創建scanner對象
System.out.println("請輸入圖書序號:");
int BookNum = input.nextInt();
if(BookNum < books.length && BookNum >= 0) {
return books[BookNum-1];
}
throw new Exception("圖書不存在!");
}
}
package exception_demo;
public class BookException extends Exception{
public BookException(String message) {
super(message);
}
}
2020-03-14
兄弟 我試了一下你的代碼,有個問題
下面這段里,當我int type輸入非數字時,比如我控制臺打一個a,為什么沒有報InputMismatchException,你的代碼運行結果是顯示null,然后重新開始,這個我想不通啊
//通過哪種類型選擇圖書
public int searchType() throws BookException {
Scanner input = new Scanner(System.in);//創建scanner對象
System.out.print("請輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
int type = input.nextInt();
if(type == 1 || type == 2) {
return type;
}else{
throw new BookException("命令輸入錯誤!請根據提示輸入數字命令!");
}
}
2020-03-13
這個是不是沒法實現報錯之后重新輸入?