InputException.java
package com.imooc.test;
public class InputException extends Exception {
public InputException() {
super();
System.out.println("命令输入错误!请根据提示输入数字命令!");
}
public InputException(String message) {
super(message);
System.out.println(message);
}
}
BookBorrow.java
package com.imooc.test;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class BookBorrow {
private static String[] books = { "高数", "积分变换", "线性代数", "马克思哲学" };
public static void main(String[] args) {
// TODO Auto-generated method stub
BookBorrow bkb = new BookBorrow();
bkb.borrow();
}
public void borrowByName(Scanner input) throws InputException {
System.out.println("输入图书名称:");
String name = input.next();
if (-1 == Arrays.binarySearch(books, name)) {
System.out.println("图书不存在!");
throw new InputException();
} else {
System.out.println("book: " + name);
}
}
public void borrowByNumber(Scanner input) throws InputException {
System.out.println("输入图书序号:");
int num = input.nextInt();
if (num < 1 || num > books.length) {
System.out.println("图书不存在!");
throw new InputException();
} else {
System.out.println("book: " + books[num - 1]);
}
}
public void borrow() {
Scanner input = new Scanner(System.in);
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
try {
switch (input.nextInt()) {
case 1:
borrowByName(input);
break;
case 2:
borrowByNumber(input);
break;
default:
System.out.println("命令输入错误!请根据提示输入数字命令!");
borrow();
break;
}
} catch(InputException e) {
}catch (InputMismatchException e) {
System.out.println("命令输入错误!请根据提示输入数字命令!");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
borrow();
input.close();
}
}
}
程序存在一些问题:1. 根据要求查询的第二步 根据书名或序号查询若输入数据格式不正确没有一个明确的提示错误的类型以及错误后应继续执行主程序的操作。2. 要求根据书名或图书序号查询查询,图书和序号应存在唯一对应关系,所以最好把数据存储在map集合中。
路过请多指教
恍恍惚惚朦朦胧