//Books.java, 处理图书查询流程的类 package com.imooc.bookmanagement; import java.util.*; public class Books { private String[] book = {new String("高数"), new String("数据结构")}; private Scanner c = null; private boolean flagNotFound = true; private int searchMethod() throws WrongCommandException{ int k = 0; System.out.println("请输入命令:1-按照名称查找图书;2-按照序号查找图书"); try{ c = new Scanner(System.in); k = c.nextInt(); if (k == 1 || k == 2){ } else{ System.out.println("命令输入错误!请根据提示输入数字命令!"); throw new WrongCommandException("命令输入错误!"); } }catch (InputMismatchException e){ throw new WrongCommandException("命令输入错误!"); } return k; } private int searchBookByName() throws BookDoesNotExistException{ int i = 0; System.out.println("请输入图书名称:"); c = new Scanner(System.in); String s = c.next(); for(i = 0; i < book.length; i++){ if(s.equals(book[i])){ return i; } } throw new BookDoesNotExistException("图书不存在!"); } private int searchBookByNumber() throws BookDoesNotExistException{ int i = 0; System.out.println("请输入图书序号:"); try{ c = new Scanner(System.in); int s = c.nextInt(); for(i = 0; i < book.length; i++){ if(s == i+1){ return i; } } throw new BookDoesNotExistException("图书不存在!"); }catch (Exception e){ throw new BookDoesNotExistException("图书不存在!"); } } public void processing(){ int bookNumber; int k = 0; while(flagNotFound){ try{ k = searchMethod(); if(k == 1){ try{ bookNumber = searchBookByName(); flagNotFound = false; System.out.println("book:"+book[bookNumber]); }catch (BookDoesNotExistException e){ System.out.println("图书不存在!"); flagNotFound = true; } } else if (k == 2){ try{ bookNumber = searchBookByNumber(); flagNotFound = false; System.out.println("book:"+book[bookNumber]); }catch (BookDoesNotExistException e){ System.out.println("图书不存在!"); flagNotFound = true; } } }catch(WrongCommandException e){ System.out.println("命令输入错误!请根据提示输入数字命令!"); flagNotFound = true; } } if(c!=null) c.close(); } }
//BookDoesNotExistException.java, 图书不存在异常类 package com.imooc.bookmanagement; public class BookDoesNotExistException extends Exception { public BookDoesNotExistException(){ } public BookDoesNotExistException(String message){ super(message); } }
//WrongCommandException.java, 错误命令异常类 package com.imooc.bookmanagement; public class WrongCommandException extends Exception { WrongCommandException(){ } WrongCommandException(String message){ super(message); } }
//BookManagement.java, 主类 package com.imooc.bookmanagement; public class BookManagement { public static void main(String[] args) { Books book1 = new Books(); book1.processing(); } }
编程思路咋就这么乱呢
还行吧
脑子好乱!!
感谢。。。