package com.library; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; public class FindBook { private static Scanner in = new Scanner(System.in); private static HashMap<String,String> bMap = new HashMap<String,String>(); public static void main(String[] args) { createBook(); try { do { find(findType()); }while(isGoingOn().equals("1")); } catch (CommandException e) { System.out.println("请输入正确命令"); new FindBook(); FindBook.main(args); } } public static void createBook() { bMap.put("1", "Java"); bMap.put("2", "C++"); bMap.put("3", "Python"); System.out.println("图书馆共有"+bMap.size()+"本书。"); } public static String findType() throws CommandException{ System.out.println("请输入查询方式:1-按书名查询 2-按书号查询"); String flag = in.next(); if(flag.equals("1")|flag.equals("2")) return flag; throw new CommandException(); } public static void find(String type) { try { if(type.equals("1")) { System.out.println("请输入书名:"); String v = in.next(); System.out.println("找到图书 书号:"+getBook(type,bMap,v)+" 书名:"+v); }else { System.out.println("请输入书号:"); String v = in.next(); System.out.println("找到图书 书号:"+v+" 书名:"+getBook(type,bMap,v)); } } catch (NoBookException e) { System.out.println("查无此书"); } catch (CommandException e) { System.out.println("请输入正确命令"); } } public static String isGoingOn() throws CommandException{ System.out.println("是否继续查找:1-查找 2-结束"); String flag = in.next(); if(flag.equals("1")|flag.equals("2")) return flag; throw new CommandException(); } public static Object getBook(String type,HashMap<String,String> map,String v) throws NoBookException,CommandException{ if(type.equals("1")) { Iterator<String> it = map.keySet().iterator(); while (it.hasNext()) { String key = it.next().toString(); if (map.get(key).equals(v)) return key; } throw new NoBookException("该图书不存在"); } else { Integer it = new Integer(v); int n = it.intValue(); if(n>map.size()) throw new NoBookException("该图书不存在"); return map.get(v); } } }
package com.library; public class NoBookException extends Exception{ private static final long serialVersionUID = 1L; public NoBookException() { } public NoBookException(String message) { super(message); } }
package com.library; public class CommandException extends Exception{ private static final long serialVersionUID = 1L; public CommandException() { } public CommandException(String message) { super(message); } }
点击查看更多内容
4人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦