Book.java
package RentBook;
public class Book {
String name;
int id;
public Book(int id, String name) {
this.id = id;
this.name = name;
}
}
CommandException.java
package RentBook;
public class CommandException extends Exception {
public CommandException() {
}
public CommandException(String e) {
super(e);
}
}
NotFoundException.java
package RentBook;
public class NotFoundException extends Exception {
public NotFoundException() {
}
public NotFoundException(String e) {
super(e);
}
}
Main.java
package RentBook;
import java.util.Scanner;
public class Main {
public void Solve() throws CommandException, NotFoundException {
Scanner scan = new Scanner(System.in);
Book[] books = {
new Book(1, "maths"),
new Book(2, "biology"),
new Book(3, "history"),
new Book(4, "computer")
};
System.out.println("请选择查询方式:1.按序号查询 2.按书名查询");
int cas = scan.nextInt();
if(cas == 1) {
System.out.println("请输入书籍序号");
int cur = scan.nextInt();
if(cur < 1 || cur > 4) {
throw new NotFoundException("图书不存在异常,请重新输入");
} else {
for(Book book : books) {
if(book.id == cur) {
System.out.println("book: " + book.name);
break;
}
}
}
} else if(cas == 2) {
System.out.println("请输入书籍名称");
String cur = scan.next();
boolean flag = false;
for(Book book : books) {
if(book.name.equals(cur)) {
System.out.println("book: " + book.name);
flag = true;
break;
}
}
if(flag == false) {
throw new NotFoundException("图书不存在异常,请重新输入");
}
} else {
throw new CommandException("错误命令异常,请重新输入");
}
}
public static void main(String[] args) {
Main main = new Main();
try {
main.Solve();
} catch(CommandException e) {
e.printStackTrace();
} catch(NotFoundException e) {
e.printStackTrace();
}
}
}
请选择查询方式:1.按序号查询 2.按书名查询
2
请输入书籍名称
chinese
RentBook.NotFoundException: 图书不存在异常,请重新输入
at RentBook.Main.Solve(Main.java:41)
at RentBook.Main.main(Main.java:51)
请选择查询方式:1.按序号查询 2.按书名查询
3
RentBook.CommandException: 错误命令异常,请重新输入
at RentBook.Main.Solve(Main.java:44)
at RentBook.Main.main(Main.java:51)
请选择查询方式:1.按序号查询 2.按书名查询
1
请输入书籍序号
5
RentBook.NotFoundException: 图书不存在异常,请重新输入
at RentBook.Main.Solve(Main.java:20)
at RentBook.Main.main(Main.java:51)
点击查看更多内容
24人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦