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)
热门评论
代码很清晰,不过有些不太严谨的地方,书籍id只判断了1到4,但是如果我输入2.5呢,抛出的异常就是系统默认的类型错误了,不是你自己定义的异常,感觉这种情况也应该自己捕获处理
你好,我有一些疑问。觉得在通过书名选择时,事先定义了flag = false,所以,无论for里边的equals结果如何,都会出现接下来的if里图书不存在的异常。这个可以怎么修改呢?
我认为写得还不错,看起来很清爽