package homework; import java.util.*; public class BookSearch { Scanner in = new Scanner(System.in); public static Book[] books = {new Book(1,"高数"),new Book(2,"操作系统"),new Book(3,"数据库"),new Book(4,"ssh"),new Book(5,"HTML5")}; public static void main(String[] args){ BookSearch a = new BookSearch(); a.choose(); } public void choose(){ int searchType = 0; while(true){ System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); try { searchType = in.nextInt(); } catch (Exception e) { // TODO: handle exception System.out.println("请输入数字!"); // in = new Scanner(System.in); 为什么注释掉这一句之后,程序会无限循环 continue; }finally{ } if(searchType == 1) { searchByName(); }else if(searchType == 2) { searchByID(); }else { System.out.println("输入有误请重新输入"); } } } public void searchByName(){ String bookName ; System.out.println("输入图书名称:"); bookName = in.next(); for(int i = 0;i < books.length; i++){ if(bookName.equals(books[i].getName())) { System.out.println("book:"+books[i].getName()); return; } }System.out.println("图书不存在"); } public void searchByID(){ int id ; System.out.println("输入图书序号:"); id = in.nextInt(); for(int i = 0;i < books.length; i++){ if(id == books[i].getID()) { System.out.println("book:"+books[i].getName()); return; } }System.out.println("图书不存在"); } }
每次重新定义Scanner对象