public class Borrow {
public static void main(String[] args) throws CommandException, NoResultException {
Borrow borrow = new Borrow();
borrow.select();
}
public void select() throws CommandException, NoResultException {
String[] books = {"西游记", "红楼梦", "水浒传", "三国演义"};
Scanner input = new Scanner(System.in);
try {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int ipt1 = input.nextInt();
if (ipt1 == 1) {
System.out.println("输入图书名称:");
String ipt2 = input.next();
String result = "";
for (String book : books) {
if (ipt2.contentEquals(book)) {
result = book;
}
}
if (result != "") {
System.out.println("book:" + result);
} else {
throw new NoResultException("图书不存在!");
}
} else if (ipt1 == 2) {
System.out.println("输入图书序号:");
int ipt3 = input.nextInt();
if (ipt3 > books.length || ipt3 <= 0) {
throw new NoResultException("图书不存在!");
} else if (ipt3 > 0 && ipt3 <= books.length) {
System.out.println("book:" + books[ipt3 - 1]);
} else {
throw new CommandException("命令输入错误!请根据提示输入数字命令!");
}
} else {
throw new CommandException("命令输入错误!请根据提示输入数字命令!");
}
} catch (CommandException e) {
System.out.println(e.getMessage());
select();
} catch (NoResultException e) {
System.out.println(e.getMessage());
select();
} catch (InputMismatchException e) {
System.out.println("命令输入错误!请根据提示输入数字命令!");
select();
}
}
}
public class CommandException extends Exception {
public CommandException() { }
public CommandException(String e) {
super(e);
}
}
public class NoResultException extends Exception {
public NoResultException() { }
public NoResultException(String e) {
super(e);
}
}