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