作業(yè)代碼
package com.imooc.test;
import java.util.Scanner;
//模擬借書系統
/*
?* 要求:
?* 1.定義字符串數組保存圖書信息
?* 2.提示用戶輸入,分別按照“書名”和"圖書序號"查找圖書
?* 3.根據輸入信息進行適當的異常處理
?* 如果輸入類型錯誤,拋出“錯誤命令異?!保⑻崾局匦螺斎?/p>
?* 如果書名不存在,拋出“圖書不存在異?!?,并提示重新輸入
?* 如果圖書序號超過字符串數組范圍,拋出“圖書不存在異?!保⑻崾局匦螺斎?/p>
?*/
public class BorrowBook {
private static Scanner input=new Scanner(System.in);
public static void main(String[] args) {
String[] books={"數據結構","高數","毛概","C語言","軟件工程"};
while(true){
System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
String book;
try {
int cmn=inputCommand();
switch(cmn){
case 1:
book=getBookName(books);
System.out.println("book:"+book);
break;
case 2:
book=getBookNum(books);
System.out.println("book:"+book);
break;
case -1:
System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
continue;
default:
System.out.println("命令輸入錯誤!");
continue;
}
break;
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
continue;
}
}
}
//按照圖書名稱查詢圖書
public static String getBookName(String[] books)throws Exception {
System.out.println("請輸入圖書名稱:");
String name=input.next();
for(int i=0;i<books.length;i++){
if(name.equals(books[i])){
return books[i];
}
}
throw new Exception("圖書不存在!");
}
public static String getBookNum(String[] books)throws Exception{
while(true){
System.out.println("輸入圖書序號:");
try {
int num=inputCommand();
if(num==-1){
System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
continue;
}
String book=books[num];
return book;
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
Exception exc=new Exception("圖書不存在!");
exc.initCause(e);
throw exc;
}
}
}
//從控制臺輸入命令,用于輸入命令和輸入圖書序號
public static int inputCommand(){
int command;
try {
command=input.nextInt();
return command;
} catch (Exception e) {
// TODO: handle exception
input=new Scanner(System.in);
return -1;
}
}
}
2014-11-27
下載。