//Books.java,?處理圖書查詢流程的類
package?com.imooc.bookmanagement;
import?java.util.*;
public?class?Books?{
private?String[]?book?=?{new?String("高數"),?new?String("數據結構")};
private?Scanner?c?=?null;
private?boolean?flagNotFound?=?true;
private?int?searchMethod()?throws?WrongCommandException{
int?k?=?0;
System.out.println("請輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
try{
c?=?new?Scanner(System.in);
k?=?c.nextInt();
if?(k?==?1?||?k?==?2){
}
else{
System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
throw?new?WrongCommandException("命令輸入錯誤!");
}
}catch?(InputMismatchException?e){
throw?new?WrongCommandException("命令輸入錯誤!");
}
return?k;
}
private?int?searchBookByName()?throws?BookDoesNotExistException{
int?i?=?0;
System.out.println("請輸入圖書名稱:");
c?=?new?Scanner(System.in);
String?s?=?c.next();
for(i?=?0;?i?<?book.length;?i++){
if(s.equals(book[i])){
return?i;
}
}
throw?new?BookDoesNotExistException("圖書不存在!");
}
private??int?searchBookByNumber()?throws?BookDoesNotExistException{
int?i?=?0;
System.out.println("請輸入圖書序號:");
try{
c?=?new?Scanner(System.in);
int?s?=?c.nextInt();
for(i?=?0;?i?<?book.length;?i++){
if(s?==?i+1){
return?i;
}
}
throw?new?BookDoesNotExistException("圖書不存在!");
}catch?(Exception?e){
throw?new?BookDoesNotExistException("圖書不存在!");
}
}
public?void?processing(){
int?bookNumber;
int?k?=?0;
while(flagNotFound){
try{
k?=?searchMethod();
if(k?==?1){
try{
bookNumber?=?searchBookByName();
flagNotFound?=?false;
System.out.println("book:"+book[bookNumber]);
}catch?(BookDoesNotExistException?e){
System.out.println("圖書不存在!");
flagNotFound?=?true;
}
}
else?if?(k?==?2){
try{
bookNumber?=?searchBookByNumber();
flagNotFound?=?false;
System.out.println("book:"+book[bookNumber]);
}catch?(BookDoesNotExistException?e){
System.out.println("圖書不存在!");
flagNotFound?=?true;
}
}
}catch(WrongCommandException?e){
System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
flagNotFound?=?true;
}
}
if(c!=null)
c.close();
}
}
//BookDoesNotExistException.java,?圖書不存在異常類
package?com.imooc.bookmanagement;
public?class?BookDoesNotExistException?extends?Exception?{
public?BookDoesNotExistException(){
}
public?BookDoesNotExistException(String?message){
super(message);
}
}
//WrongCommandException.java,?錯誤命令異常類
package?com.imooc.bookmanagement;
public?class?WrongCommandException?extends?Exception?{
WrongCommandException(){
}
WrongCommandException(String?message){
super(message);
}
}
//BookManagement.java,?主類
package?com.imooc.bookmanagement;
public?class?BookManagement?{
public?static?void?main(String[]?args)?{
Books?book1?=?new?Books();
book1.processing();
}
}
2018-07-30
編程思路咋就這么亂呢
2017-07-02
還行吧
2017-05-08
腦子好亂!!
2015-10-15
感謝。。。