package?homework;
import?java.util.*;
public?class?BookSearch?{
Scanner?in?=?new?Scanner(System.in);
public?static?Book[]?books?=?{new?Book(1,"高數(shù)"),new?Book(2,"操作系統(tǒng)"),new?Book(3,"數(shù)據(jù)庫"),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-按照序號(hào)查找圖書");
?try?{
searchType?=?in.nextInt();
}?catch?(Exception?e)?{
//?TODO:?handle?exception
System.out.println("請(qǐng)輸入數(shù)字!");
// in?=?new?Scanner(System.in);?為什么注釋掉這一句之后,程序會(huì)無限循環(huán)
continue;
}finally{
}
?
?if(searchType?==?1)
?{
?searchByName();
?}else?if(searchType?==?2)
?{
?searchByID();
?}else
?{
?System.out.println("輸入有誤請(qǐng)重新輸入");
?}
?}
}
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("輸入圖書序號(hào):");
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("圖書不存在");
}
}
2015-08-04
每次重新定義Scanner對(duì)象