各位大神:交流下作业心得,烦请大家提提意见!
以下为源文件:
package three1;
import java.util.InputMismatchException;
import java.util.Scanner;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
public class LibrarySystem {
// 图书馆现有书目
private String[] books = {"高数","大物","英语"};
// 按序号查找图书
public void findABook( int num ){
try{
System.out.println("book:" + books[num]);
}catch (InputMismatchException e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("图书不存在!");
}
}
// 按书名查找图书
public boolean findABook( String bookName ){
for( String book:books){
if(book.equalsIgnoreCase(bookName)){
System.out.println("book:" + book);
return true;
}
}
System.out.println("图书不存在!");
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LibrarySystem ls = new LibrarySystem();
Scanner sc = new Scanner(System.in);
while(sc != null){
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书。");
try{
int commandNum = sc.nextInt();
sc.nextLine();
switch (commandNum) {
case 1:
System.out.println("输入图书名称:");
String bookName = sc.nextLine();
ls.findABook(bookName);
break;
case 2:
System.out.println("输入图书序号:");
int bookNum = sc.nextInt();
sc.nextLine();
ls.findABook(bookNum);
break;
default:
//输入整数范围有误,抛出异常
throw new Exception("0命令输入错误!请根据提示输入数字命令!");
}
}catch(InputMismatchException e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
sc.nextLine();
}catch (Exception e){
//e.printStackTrace();
System.out.println("命令输入错误!请根据提示输入数字命令!");
}
}
}
}