- 定义了三个类
- ErrorCodeException.java
public class ErrorCodeException extends Exception {
public ErrorCodeException(){
}
public ErrorCodeException(String message){
super(message);
}
}
- NoExitBookException.java
public class NoExitBookException extends Exception {
public NoExitBookException() {
}
public NoExitBookException(String message) {
super(message);
}
}
- BorrowBookSystem.java
public class BorrowBookSystem {
String[] library = {"Java", "Python", "javascript", "Android", "iOS", "Linux", "Unix", "C", "C++", "C#", "Ruby", "Django", "Flask"};
public static void main(String[] args) {
BorrowBookSystem system = new BorrowBookSystem();
system.borrow();
}
public void borrow() {
while (true) {
int command = 0;
try {
command = command();
} catch (ErrorCodeException e) {
System.out.println(e.getMessage());
}
if (command == 1) {
try {
queryBookName();
} catch (NoExitBookException e) {
System.out.println(e.getMessage());
}
} else if (command == 2) {
try {
queryBookCode();
} catch (ErrorCodeException e) {
System.out.println(e.getMessage());
} catch (NoExitBookException e) {
System.out.println(e.getMessage());
}
}
}
}
public int command() throws ErrorCodeException {
int result;
System.out.println("输入查询命令:1-按照图书名称查询,2-按照图书序列号查询。");
Scanner scanner = new Scanner(System.in);
String command = scanner.next().trim();
if (command.equals("1")) {
result = 1;
} else if (command.equals("2")) {
result = 2;
} else {
throw new ErrorCodeException("命令输入错误!请根据提示输入数字命令!");
}
return result;
}
private void queryBookCode() throws ErrorCodeException, NoExitBookException {
System.out.println("输入图书序列号:");
Scanner scanner = new Scanner(System.in);
String next = scanner.next().trim();
int number;
try {
number = Integer.parseInt(next);
} catch (Exception e) {
throw new ErrorCodeException("命令输入错误!请根据提示输入数字命令!");
}
try {
String bookName = library[number];
System.out.println("book:" + bookName);
} catch (Exception e) {
throw new ErrorCodeException("图书不存在!");
}
}
private void queryBookName() throws NoExitBookException {
System.out.println("输入图书名称:");
Scanner scanner = new Scanner(System.in);
String next = scanner.next().trim();
boolean result = false;
for (int i = 0; i < library.length; i++) {
if (library[i].equals(next)) {
System.out.println("book:" + library[i]);
result = true;
break;
}
}
if (!result) {
throw new NoExitBookException("图书不存在!");
}
}
}
点击查看更多内容
22人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦