package com.lendbook;
import java.util.Scanner;
public class LendBook {
static Scanner scanner = 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:" + book);
break;
case 2:
book = getBookByNumber(books);
System.out.println("book:" + book);
break;
case -1:
System.out.println("输入有错!请根据提示重新输入!");
continue;
default:
System.out.println("命令输入错误!");
continue;
}
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
}
}
private static String getBookByName(String[] books) throws Exception {
System.out.println("输入图书名称:");
String name=scanner.nextLine();
for(String book:books){
if(book.equals(name))
return book;
}
throw new Exception("图书不存在!");
}
private static String getBookByNumber(String[] books) throws Exception{
while(true){
System.out.println("输入图书序号:");
try{
int index=inputCommand();
if(index==-1){
System.out.println("输入有错!请根据提示重新输入!");
continue;
}
String book=books[index];
return book;
}catch(ArrayIndexOutOfBoundsException e){
Exception bookNotExist=new Exception("图书不存在!");
bookNotExist.initCause(e);
throw bookNotExist;
}
}
}
private static int inputCommand() {
int command;
try {
command = Integer.parseInt(scanner.nextLine());
return command;
} catch (Exception e) {
return -1;
}
}
}
打开App,阅读手记