老師代碼中 按序號查找圖書方法中 (index-1)更有利于用戶需求
package com.imooc;
import java.util.Scanner;
public class BBB {
private static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
//定義圖書數組,保存圖書信息
String[] books={"C語言", "數據結構", "匯編語言", "高數", "大學語文", "毛概"};
while(true){
System.out.println("請輸入要查找圖書的方式:1-按照圖書名稱查找,2-按照圖書序列號查找");
String book;
try{
//取得整型命令
int command=inputCommand();
//根據不同的命令值,進行不同的操作
switch(command){
case 1://按照圖書名稱選擇圖書
book=getBookByName(books);
System.out.println("請輸入圖書的名稱: "+book);
break;
case 2://按照圖書序號(數組下標)選擇圖書
book=getBookByNumber(books);
System.out.println("請輸入圖書的序號: "+book);
break;
case -1://返回值為-1,說明輸入有誤
System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
break;
default://其他值命令均為錯誤命令
System.out.println("命令輸入有誤!");
continue;
}
}catch(Exception bne){
}
}
}
//按照圖書序號查找該圖書
private static String getBookByNumber(String[] books) throws Exception{
// TODO Auto-generated method stub
while(true){
System.out.println("請輸入改圖書的序號: ");
try{
//獲取圖書序號(數組下標)
int index=inputCommand();
//若返回值為-1
if(index==-1){
System.out.println("命令輸入有誤,請根據提示輸入正確的數字命令");
continue;
}
//若不出現"數組下標越界異常",則返回相應位置的圖書
String book=books[index-1];//這里最好用index-1
return book;
}catch(ArrayIndexOutOfBoundsException e){
//輸入的序號不存在(引發"數組下標越界異常"),則拋出"圖書不存在異常"
Exception bookNotExists=new Exception("圖書不存在!");
bookNotExists.initCause(e);
throw bookNotExists;
}
}
}
//按照圖書名稱查詢圖書
private static String getBookByName(String[] books) throws Exception{
// TODO Auto-generated method stub
System.out.println("請輸入圖書名稱: ");
//獲取輸入的圖書名稱
String name=console.next();
for(int i=0;i<books.length;i++){
if(name.equals(books[i])){
//輸入的名稱與圖書名稱相匹配,返回該圖書
return books[i];
}
}
//若無匹配,拋出"無數不存在"異常
throw new Exception("圖書不存在");
}
private static int inputCommand() {
// TODO Auto-generated method stub
int command;
try{
command=console.nextInt();
return command;
}catch(Exception e){
//若輸入的是字符或者字符串則拋出異常,捕獲該異常,拋出"錯誤命令異常"
console=new Scanner(System.in);
//返回-1
return -1;
}
}
}
2016-08-29
是。我在項目中也這么做的。1就是第一個元素,此元素索引是0,以此類推,索引總比輸入的少一個,index-1.