图书类
public class Book {
public String bookname;
public int booknum;
Book(String bookname,int booknum){
this.bookname=bookname;
this.booknum=booknum;
}
}
自定义异常类
public class NoexistException extends Exception {
public NoexistException () {};
public NoexistException (String message) {
super(message);
};
}
主程序
import java.util.Scanner;
public class borrowbook {
public static void main(String[] args) {
// TODO Auto-generated method stub
Book book[] = { new Book("高数", 1), new Book("数据结构", 2) };
while(true){
System.out.println("请输入数字命令:1-按照书名查找图书;2-按照序号查找图书");
Scanner sn = new Scanner(System.in);
try {
int input_in = sn.nextInt();
if (input_in == 2) {
System.out.println("请输入图书序号:");
int input_in_num = sn.nextInt();
boolean num = false;
for (int i = 0; i < book.length; i++) {
if (input_in_num == book[i].booknum) {
System.out.println("book:" + book[i].booknum);
num = true;
}
}
if (!num) {
warn();
}
} else if(input_in == 1) {
System.out.println("请输入图书名称:");
String input_in_name = sn.next();
boolean name = false;
for (int i = 0; i < book.length; i++) {
if (input_in_name.equals(book[i].bookname)) {
System.out.println("book:" + book[i].bookname);
name = true;
}
}
if (!name) {
warn();
}
}
else {
System.out.println("命令输入错误!请输入数字命令!");
}
} catch (NoexistException e) {
// TODO: handle exception
System.out.println("图书不存在!");
} catch (Exception e) {
// TODO: handle exception
System.out.println("命令输入错误!请输入数字命令!");
}
}
}
public static void warn() throws NoexistException {
throw new NoexistException("图书不存在!");
}
}
运行结果
请输入数字命令:1-按照书名查找图书;2-按照序号查找图书
1
请输入图书名称:
4
图书不存在!
请输入数字命令:1-按照书名查找图书;2-按照序号查找图书
1
请输入图书名称:
高数
book:高数
请输入数字命令:1-按照书名查找图书;2-按照序号查找图书
热门评论
你这个代码的Exception e好像根本没用到,只是else { System.out.println("命令输入错误!请输入数字命令!"); 这里判断一开始是否输入错误的数字命令
boolean num=false;和num=true;是什么意思啊,搞不懂
throw new NoexistException("图书不存在!");
想知道这样是什么意思