慕雪8679015
2020-02-26 12:46
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);
}
}
兄弟 我试了一下你的代码,有个问题
下面这段里,当我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("命令输入错误!请根据提示输入数字命令!");
}
}
这个是不是没法实现报错之后重新输入?
Java入门第三季
409792 学习 · 4340 问题
相似问题