模擬借書(shū)系統(tǒng)
標(biāo)簽:
數(shù)據(jù)結(jié)構(gòu)
package imooc;
import java.util.Scanner;
public class Book {
public static Scanner inputScanner = new Scanner(System.in);
public static void main(String[] args) {
String[] bookStrings = { "数据结构", "c语言", "操作系统", "英语" };
String book;
while (true) {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
try {
int command = inputCommand();
switch (command) {
case 1:
book = getbookByname(bookStrings);
System.out.println("book:" + book);
break;
case 2:
book = getBookById(bookStrings);
System.out.println("book:" + book);
break;
case -1:
System.out.println("命令输入错误,请根据提示输入数字命令!");
continue;
default:
System.out.println("命令输入错误!");
continue;
}
break;
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
continue;// continue只能在循环里使用,若输入错误则再重新循环指令进行输入
}
}
}
// 按名称查找
private static String getbookByname(String[] books) throws Exception {
System.out.println("请输入图书名称");
String nameString = inputScanner.next();
for (int i = 0; i < books.length; i++) {
if (nameString.equals(books[i]))
return nameString;
}
throw new Exception("图书不存在");
}
// 按序号查找
private static String getBookById(String[] books) throws Exception {
while (true) {
System.out.println("请输入图书序号");
try {
int index = inputScanner.nextInt();
if (index == -1) {
System.out.println("命令行输入错误!请根据提示输入数字命令");
}
String bookString=books[index];
return bookString;
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
Exception bookNotExists =new Exception("图书不存在");
bookNotExists.initCause(e);
throw bookNotExists;
}
}
}
// 获得外键输入的选择
private static int inputCommand() {
int command;
try {
command = inputScanner.nextInt();
return command;
} catch (Exception e) {
// TODO: handle exception
inputScanner = new Scanner(System.in);
return -1;
}
}
}
點(diǎn)擊查看更多內(nèi)容
27人點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得
100積分直接送
付費(fèi)專(zhuān)欄免費(fèi)學(xué)
大額優(yōu)惠券免費(fèi)領(lǐng)