package com.bookmanage;
public class CommandErrorException extends Exception{
public CommandErrorException() {
}
public CommandErrorException (String message) {
super(message);
}
}
package com.bookmanage;
public class BookNotExistException extends Exception {
public BookNotExistException() {
// TODO Auto-generated constructor stub
}
public BookNotExistException(String message){
super(message);
}
}
package com.bookmanage;
public class Books {
private String name;//图书名称
private int orderNum;//图书序号
public Books(String name, int orderNum) {
// TODO Auto-generated constructor stub
this.name = name;
this.orderNum = orderNum;
}
public String getName() {
return name;
}
public int getOrderNum() {
return orderNum;
}
}
package com.bookmanage;
import java.util.InputMismatchException;
import java.util.Scanner;
public class BookCheck {
//定义图书数组
public static Books[] books = { new Books("高等数学", 1), new Books("大学英语", 2),
new Books("数据结构", 3), new Books("算法导论", 4), new Books("编程基础", 5),
new Books("线性代数", 6)};
//定义用于接收控制台输入的变量
public static Scanner inputScanner = new Scanner(System.in);
//图书是否查找到的标记变量
public static boolean flagNotFound = true;
//判断查找方式
private static int searchMethod() throws CommandErrorException {
int methodKey = 0;
try {
methodKey = inputScanner.nextInt();//获取输入命令
if (methodKey==1 methodKey==2) {
}else {
throw new CommandErrorException("命令输入错误!");
}
} catch (InputMismatchException e) {
inputScanner = new Scanner(System.in);
throw new CommandErrorException("命令输入错误!");
}
return methodKey;
}
//按名称查找图书
public static int byName(String name) throws BookNotExistException{
int num = 0;//记录查找到的图书的数组下标
for (int i = 0; i < books.length; i++) {
if (name.equals(books[i].getName())) {
num = i;
return num;
}
}
throw new BookNotExistException("图书不存在!");
}
//按序号查找图书
public static int byNum(int orderNum) throws BookNotExistException {
int num = 0;//记录查找到的图书的数组下标
for (int i = 0; i < books.length; i++) {
if (orderNum == books[i].getOrderNum()) {
num = i;
return num;
}
}
throw new BookNotExistException("图书不存在!");
}
public static void main(String[] args) {
int bookNumber = 0;
int methodNumber = 0;
while (flagNotFound) {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
try {
methodNumber = searchMethod();
if (methodNumber==1) {
System.out.println("输入图书名称:");
try {
bookNumber = byName(inputScanner.next());
flagNotFound = false;
System.out.println("book:"+"["+books[bookNumber].getOrderNum()+"] "+books[bookNumber].getName());
} catch (BookNotExistException e) {
System.out.println("图书不存在!");
flagNotFound = true;
}
}else if (methodNumber == 2) {
System.out.println("输入图书序号:");
try {
bookNumber = byNum(inputScanner.nextInt());
flagNotFound = false;
System.out.println("book:"+"["+books[bookNumber].getOrderNum()+"] "+books[bookNumber].getName());
} catch (BookNotExistException e) {
System.out.println("图书不存在!");
flagNotFound = true;
}
}
} catch (CommandErrorException e) {
System.out.println("命令输入错误!请根据提示数字输入命令!");
flagNotFound = true;
}
}
inputScanner.close();
}
}
打开App,阅读手记