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;
}
}
}
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦