java语言实现一个控制台版的模拟借书系统。
目标
用java语言实现一个控制台版的模拟借书系统,旨在练习java异常机制。
要求
成品
参考代码及注释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| package com.jinger;
import java.util.Scanner;
public class BookManagerEasy { private static Scanner console = new Scanner(System.in);
public static void main(String[] args) { String[] books = { "C语言", "数据结构", "汇编语言", "高数", "大学语文", "毛概" }; while (true) { System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); String book; try { int command = inputCommand(); switch (command) { case 1: book = getBookByName(books); System.out.println("book:" + book); break; case 2: book = getBookByNumber(books); System.out.println("book:" + book); break; case -1: System.out.println("命令输入错误!请根据提示输入数字命令!"); continue; default: System.out.println("命令输入错误!"); continue; } break; } catch (Exception bne) { System.out.println(bne.getMessage()); continue; } } }
private static String getBookByName(String[] books) throws Exception { System.out.println("输入图书名称:"); String name = console.next(); for (int i = 0; i < books.length; i++) { if (name.equals(books[i])) return books[i]; } throw new Exception("图书不存在!"); }
private static String getBookByNumber(String[] books) throws Exception { while (true) { System.out.println("输入图书序号:"); try { int index = inputCommand(); if(index == -1){ System.out.println("命令输入错误!请根据提示输入数字命令!"); continue; } String book = books[index]; return book; } catch (ArrayIndexOutOfBoundsException e) { Exception bookNotExists = new Exception("图书不存在!"); bookNotExists.initCause(e); throw bookNotExists; } } }
private static int inputCommand(){ int command; try { command = console.nextInt(); return command; } catch (Exception e) { console = new Scanner(System.in); return -1; } } }
|