实现的图书借阅系统要处理用户输入的非法参数,并引导用户正确使用
测试结果:
主要目的就是练习异常处理中的Exception类的使用
使用的相关语法
1 try{2 //可能产生异常的代码块3 }catch(Exception e){4 //处理异常的代码块5 }finally{ //可以根据需要选择6 //最终执行的代码块7 }
实现过程:
创建BorrowBook类
import java.util.InputMismatchException;import java.util.Scanner;public class BorrowBook { Scanner scn = new Scanner(System.in);}
定义三种异常类:输入的编号没有对应图书的异常、输入的书名没有对应的图书的异常、其他正常异常
private static class commanException extends Exception{ private commanException() {}}private static class bookNumException extends Exception{ private bookNumException() {}}private static class bookNameException extends Exception{ private bookNameException() {}}
创建抛出异常方法,并抛出三种异常
private void commanExc() throws commanException{ throw new commanException();}private void bookNumExc() throws bookNumException{ throw new bookNumException();}private void bookNameExc() throws bookNameException{ throw new bookNameException();}
创建用于存储图书的Box的方法(以两类书为例)
private static String[] bookBox() { String[] bookBox = new String[] {"高数","线性代数"}; return bookBox;}
创建借书入口方法
private static void borrowBook() throws Exception{ System.out.println("输入命令:1-根据名称查找图书;2-根据序号查找图书"); try { int inputNum = new BorrowBook().scn.nextInt(); try { if(inputNum == 0) { borrowBkByName(bookBox()); }else if(inputNum == 1){ borrowBkByNum(bookBox()); }else { new BorrowBook().commanExc(); } }catch(Exception e){ System.out.println("命令输入错误,请根据提示输入数字命令!"); borrowBook(); } }catch(InputMismatchException eInput) { System.out.println("命令输入错误,请根据提示输入数字命令!"); borrowBook(); }}
创建依据书名借书的方法
private static void borrowBkByName(String[] books) throws Exception{ System.out.println("输入图书名称:"); String bookName = new BorrowBook().scn.next(); try { switch(bookName) { case "高数": System.out.println("book:" + bookName); break; case "线性代数": System.out.println("book:" + bookName); break; default: new BorrowBook().bookNameExc(); } }catch(Exception e) { System.out.println("图书不存在!"); borrowBkByName(books); } }
创建依据图书序号借书的方法
private static void borrowBkByNum(String[] books) throws Exception{ System.out.println("输入图书序号:"); try { int bookNum = new BorrowBook().scn.nextInt(); try { switch(bookNum) { case 1: System.out.println("book:" + books[bookNum]); break; case 2: System.out.println("book:" + books[bookNum]); break; default: new BorrowBook().bookNumExc(); } }catch(Exception e) { System.out.println("图书不存在!"); borrowBkByNum(books); } }catch(InputMismatchException e) { System.out.println("命令输入错误,请根据提示输入数字命令!"); borrowBkByNum(books); }}
用于初始化的main方法
public static void main(String[] args) throws Exception{ borrowBook(); new BorrowBook().scn.close();}