不知道怎么去处理循环
package library; import java.util.InputMismatchException; import java.util.Scanner; public class tushu { public static String[] books = { "高数", "代数", "英语", "语文" }; public static String byBookName(String filterName) { for (String book : books) { if (book.contains(filterName)) { return book; } } return "不存在"; } public static String byBookID(int bookID) { return books[bookID - 1]; } public static void main(String[] args) { System.out.println("输入命令: 1-按照名称查找图书; 2-按照序号查找图书"); Scanner scanner = new Scanner(System.in); // 当输入的值为非1和非2的时候, 提示重新输入! int filterType = 0; int i = 0; do { if (i != 0) { System.out.println("命令输入错误! 请根据提示输入数字命令!"); } i++; try { filterType = scanner.nextInt(); } catch (InputMismatchException e) { scanner = new Scanner(System.in); } } while (filterType != 1 && filterType != 2); //进入查找图书的流程 if (filterType == 1) { System.out.println("输入图书名称:"); String bookName = byBookName(scanner.next()); if (bookName.equals("不存在")) { System.out.println("图书不存在!"); } else { System.out.println("book:" + bookName); } } else { System.out.println("输入图书序号:"); try { String bookName = byBookID(scanner.nextInt()); System.out.println("book:" + bookName); } catch (InputMismatchException e) { System.out.println("输入类型错误, 抛出错误命令异常, 提示重新输入"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("图书不存在!"); } scanner.close(); } } }
老师的代码
while (true) { System.out.println("输入图书序号:"); try { //获取输入的图书序号(数组下标) int index = inputCommand(); //若返回值为-1 if(index == -1){ System.out.println("命令输入错误!请根据提示输入数字命令!"); continue; } //若不出现”数组下标越界异常“,则返回相应位置的图书 String book = books[index]; return book; } catch (ArrayIndexOutOfBoundsException e) { //输入的序号不存在(引发”数组下标越界异常“),则抛出”图书不存在异常“ Exception bookNotExists = new Exception("图书不存在!"); bookNotExists.initCause(e); throw bookNotExists; } }