package com.kandy.class8;
public class Book {
private String name;
private int id;
public String getName() {
return name;
}
public Book(int id,String name) {
this.name = name;
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.kandy.class8;
public class BookNotFindExeption extends Exception{
public BookNotFindExeption(){}
public BookNotFindExeption(String message) {
super(message);
}
}
package com.kandy.class8;
import java.util.Scanner;
public class InitialBook {
//创建图书
Book[] books = {
new Book(1, "语文"),
new Book(2, "数学"),
new Book(3, "英语"),
};
//输入
Scanner input;
//显示图书菜单,进入查找分类
public void showMenu() {
try {
System.out.println("借书请按编号或书名(1:按编号/2:按书名)");
System.out.println("编号\t\t 书名");
for (Book book : books) {
System.out.println(" " + book.getId() + "\t\t《" + book.getName() + "》");
}
System.out.print("请输入1或2,0退出:");
input = new Scanner(System.in);
int num = input.nextInt();
switch (num) {
case 0:
System.exit(0);
break;
case 1:
findForId();
break;
case 2:
findForName();
break;
default:
showMenu();
}
} catch (Exception e) {
System.out.println("输入有误,请根据提示输入。");
showMenu();
} finally {
input.close();
}
}
//按编号查找
public void findForId() {
try {
System.out.print("请输入图书的编号,输入0返回上一级:");
input = new Scanner(System.in);
int num = input.nextInt();
if (num == 0) showMenu();
boolean isFind = false;
for (Book book : books) {
if (book.getId() == num) {
isFind = true;
System.out.println("********找到图书:(编号:" + book.getId() + "书名:" + book.getName() + ")");
showMenu();
break;
}
}
if (!isFind) {
throw new BookNotFindExeption("未找到此编号的图书!");
}
} catch (BookNotFindExeption e) {
System.out.println(e.getMessage());
findForId();
} catch (Exception e) {
System.out.println("输入有误,请根据提示输入。");
findForId();
} finally {
input.close();
}
}
//按书名查找
public void findForName() {
try {
System.out.print("请输入图书的名称,输入0返回上一级:");
input = new Scanner(System.in);
String name = input.nextLine();
if (name.equals("0")) showMenu();
boolean isFind = false;
for (Book book : books) {
if (book.getName().equals(name)) {
isFind = true;
System.out.println("*********找到图书:(编号:" + book.getId() + "书名:" + book.getName() + ")");
showMenu();
break;
}
}
if (!isFind) {
throw new BookNotFindExeption("未找到此名称的图书!");
}
} catch (BookNotFindExeption e) {
System.out.println(e.getMessage());
findForName();
} catch (Exception e) {
System.out.println("输入有误,请根据提示输入。");
findForName();
} finally {
input.close();
}
}
//程序入口
public static void main(String[] args) {
InitialBook in = new InitialBook();
//显示图书列表
in.showMenu();
}
}