首先是 三个自定义异常
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;
}
}
}
}
共同学习,写下你的评论
评论加载中...
作者其他优质文章