继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

不告诉你哈
关注TA
已关注
手记 4
粉丝 1
获赞 4

首先是 三个自定义异常
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;
}
}
}

}

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP