package com.study.bookstudy;
public class Main {//主函数类
public static void main(String[] args) {
Library library = new Library();
library.run();
}
}
package com.study.bookstudy;
public class Book {//Book类,基本的数据封装
private int num;
private String name;
public Book(int num, String name) {
this.num = num;
this.name = name;
}
public int getNum() {
return num;
}
public String getName() {
return name;
}
}
package com.study.bookstudy;
public class BookNotExistException extends Exception {
//自定义异常类 - 图书不存在异常
public BookNotExistException() {
System.out.println("图书不存在,请重新输入。");
}
}
package com.study.bookstudy;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class Library {//最主要的类,管理图书,以及处理搜索请求
private List<Book> books;
private Scanner scanner;
public Library() {
books = new ArrayList<Book>();
scanner = new Scanner(System.in);
init();
}
public void run() {//启动图书馆类,也可以扩展其他业务
searchService();
System.out.println("谢谢使用!");
}
private void searchService() {//搜索服务
Book book = null;
while (true) {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int choose = getRightNumber();
switch (choose) {// 写成switch形式,便于以后功能扩展
case 1:
System.out.println("输入图书名称:");
String searchStr = scanner.next();
try {
book = searchByName(searchStr);
showBookInfo(book);
return;
} catch (BookNotExistException e) {
continue;
}
case 2:
System.out.println("输入图书编号:");
int searchNum = getRightNumber();
try {
book = searchByNum(searchNum);
showBookInfo(book);
return;
} catch (BookNotExistException e) {
continue;
}
default:
break;
}
}
}
//顾名思义,通过名字搜索
private Book searchByName(String name) throws BookNotExistException {
for (Book book : books) {
if (book.getName().equals(name)) {
return book;
}
}
throw new BookNotExistException();
}
//顾名思义,通过编号搜索
private Book searchByNum(int num) throws BookNotExistException {
for (Book book : books) {
if (book.getNum() == num) {
return book;
}
}
if (num > books.size() || num < 1) {
throw new BookNotExistException();
}
return null;
}
//获得正确的数字输入
private int getRightNumber() {
int choose;
while (true) {
try {
choose = scanner.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("命令错误,请重新输入。");
scanner.next();// 清楚缓冲区无效的string字符
}
}
return choose;
}
//显示信息
private void showBookInfo(Book book) {
System.out.println("编号:" + book.getNum() + "\t书名:" + book.getName());
}
//初始化数据
private void init() {
books.add(new Book(1, "book_1"));
books.add(new Book(2, "book_2"));
books.add(new Book(3, "book_3"));
books.add(new Book(4, "book_4"));
books.add(new Book(5, "book_5"));
books.add(new Book(6, "book_6"));
}
}