异常页
package book; public class NoBook extends Exception { public NoBook(){ } public NoBook(String message){ super(message); } }
主页
package book; import java.util.InputMismatchException; import java.util.Scanner; public class BookTest { public static void main(String[] args) { BookTest test = new BookTest(); test.trys(); } public void trys(){ try { showbooks(); } catch (InputMismatchException e) { System.out.println("请输入数字"); trys(); }catch (NoBook e){ System.out.println(e); trys(); } } public void showbooks() throws NoBook{ Scanner input = new Scanner(System.in); String[] books = {"book1", "book2", "book3", "book4"}; for(int i=0;i<books.length;i++){ System.out.print(i+1+":"+books[i]+" "); } System.out.println(); System.out.println("输入命令:1按照名称查找图书 2按照序号查找图书"); int num = input.nextInt(); int hasbook=0; if (num == 1) { System.out.println("请输入图书名"); String bookname=input.next(); for(String value:books){ if(value.equals(bookname)){ hasbook=1; } } if(hasbook==1){ System.out.println("书名:" + bookname); }else{ throw new NoBook("图书不存在"); } } else if (num == 2) { System.out.println("请输入图书序号"); int index = input.nextInt(); if(index>books.length){ throw new NoBook("图书不存在"); }else{ System.out.println("书名:" + books[index-1]); } } else { throw new NoBook("输入错误,请重新输入"); } } }
按你的代码,当提示输入错误之后,是不是就不能再输入了?
每次执行完throw new NoBook("输入错误,请重新输入");之后程序就结束了,是不是得重跑程序才能继续输入正确的啊
我看不出来