为了账号安全,请及时绑定邮箱和手机立即绑定

java入门第三季第一章编程练习——模拟借书系统

标签:
Java

首先是 三个自定义异常
public class CountErrorException extends Exception{
public CountErrorException(){
}
public CountErrorException(String message) {
super(message);
}
}

public class NoNameException extends Exception {
public NoNameException(){
}
public NoNameException(String message){
super(message);
}
}

public class NoNumberException extends Exception{
public NoNumberException(){
}
public NoNumberException(String message){
super(message);
}
}

然后是Book.java
public class Book {
private int number;
private String name;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Book(int number,String name){
this.number=number;
this.name=name;
}
}

最后是实现类
import java.util.Scanner;

public class Go {
public boolean getNameFound(Book[] books, Scanner scanner)
throws NoNameException, NoNumberException, CountErrorException {
try {
String name = scanner.next();
boolean a=true;//判断是否需要抛出异常
//遍历查看有无此书名的书
for (Book book : books) {
if (book.getName().equals(name)) {
System.out.println("book:" + book.getName());
a=false;
}
}
if (a) {
throw new NoNameException("图书不存在!!!");
}
} catch (NoNameException e) {
System.out.println(e.getMessage());
return true;
}
return false;
}
public boolean getNumberFound(Book[] books, Scanner scanner) throws NoNameException, NoNumberException {
try {
int number = scanner.nextInt();
boolean a=true;//判断是否需要抛出异常
for (Book book : books) {
if (book.getNumber() == number) {
System.out.println("book:" + book.getName());
a=false;
}
}
if (a) {
throw new NoNumberException("图书不存在!!");
}
} catch (NoNumberException e) {
System.out.println(e.getMessage());
return true;
}
return false;
}
public static void main(String[] args) throws NoNameException, NoNumberException, CountErrorException {
Scanner scanner = new Scanner(System.in);
Go go = new Go();
Book[] books = new Book[] { new Book(1, "语文"), new Book(2, "数学"), new Book(3, "英语") };
boolean result = false;
while (true) {
try {
System.out.println("输入命令: 1-按照名称查找图书 ; 2-按照序号查找图书");
String b = scanner.next();
if (!b.equals("1")&& !b.equals("2")) {
//抛出错误命令异常
throw new CountErrorException("命令输入错误!请根据提示输入数字");
}
// 按照名称查找
if (b.equals("1")) {
System.out.println("输入图书名称:");
result = go.getNameFound(books, scanner);
}
// 按照序号查找
if (b.equals("2")) {
System.out.println("输入图书序号:");
result = go.getNumberFound(books, scanner);
}
if (result) {
//结束本次结束操作,返回第一部
continue;
}
break;
} catch (CountErrorException e) {
System.out.println(e.getMessage());
continue;
}
}
}

}

点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消