DarkHorseCele
2015-05-12 17:56
Book类
package com.library; public class 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.library; public class BookIsNotExistException extends Exception { //自定义异常,图书不存在 public BookIsNotExistException() { System.out.println("图书不存在,请重新输入!"); } }
搜寻图书类
package com.library; import java.util.Scanner; import java.util.InputMismatchException; public class SearchBook { private Scanner input = new Scanner(System.in); //运行 public void Run() { Search(); } //搜索图书 private void Search() { while(true) { int choice=0; System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); try { choice = input.nextInt(); } catch (InputMismatchException e) { // 输入有误,重新输入 System.out.println("命令输入错误,请根据提示输入数字命令!"); input.next(); continue; } switch(choice) { //按照名称查找图书 case 1: System.out.println("输入图书名称:"); String searchStr = input.next(); try { Book book = searchByName(searchStr); ShowBookInfo(book); break; } catch (BookIsNotExistException e) { // 图书不存在 continue; } //按照序号查找图书 case 2: System.out.println("输入图书编号:"); int SearchNum = input.nextInt(); try { Book book = searchByNum(SearchNum); ShowBookInfo(book); break; } catch (Exception e) { // 图书不存在 continue; } default: System.out.println("命令输入错误,请根据提示输入数字命令!"); break; } } } //通过名字搜索图书,抛出异常 private Book searchByName(String name) throws BookIsNotExistException { for (Book book : initialize.books) { if (book.getName().equals(name)) { return book; } } throw new BookIsNotExistException(); } //通过编号搜索图书,抛出异常 private Book searchByNum(int num) throws BookIsNotExistException { for (Book book : initialize.books) { if (book.getNum()==num) { return book; } if (num > initialize.books.length || num < 1) { throw new BookIsNotExistException(); } } return null; } //显示搜索到的图书信息 private void ShowBookInfo(Book book) { System.out.println("编号:" + book.getNum() + "\t书名:" + book.getName()); } }
实现类
package com.library; public class initialize { static Book[] books = {new Book(1, "数据结构"), new Book(2, "离散数学"),new Book(3, "计算机网络"),new Book(4, "高等数学")}; public static void main(String[] args) { SearchBook s = new SearchBook(); s.Run(); } }
没问题,挺清晰的
Java入门第三季
409792 学习 · 4340 问题
相似问题