效果图:
copy到项目下,运行Client.java即可。
Client.java
package views;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Client client = new Client();
Scanner input = new Scanner(System.in);
Library library = new Library();
System.out.println("进入图书系统:1是 else否");
if (input.nextInt() == 1) {
for (;;) {
System.out.println("--------图书系统--------");
System.out.println("选择查询方式:1书名 2编号 0退出");
boolean existFlag = true;
boolean exitFlag = false;
switch (input.nextInt()) {
case 1:
System.out.println("请输入图书名称:");
// input.nextLine(); // input.nextLine()目的在于消掉回车\n
String bookName = input.next();
try {
// System.out.println("查找中....");
for (int i = 0; i < library.Books.length; i++) {
if (library.Books[i][1].equals(bookName)) {
System.out.println("图书编号:" + library.Books[i][0] + "图书名称:" + bookName);
existFlag = false;
break;
}
}
if (existFlag) {
client.exception1();
}
} catch (BookNoExistException e) {
System.err.println("图书不存在");
}finally { // 针对异常处理时输出信息不是很及时,做100ms延迟
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
break;
case 2:
System.out.println("请输入图书编号:");
String bookNum = input.next();
try {
// System.out.println("查找中....");
for (int i = 0; i < library.Books.length; i++) {
if (library.Books[i][0].equals(bookNum)) {
System.out.println("图书编号:" + library.Books[i][0] + "图书名称:" + library.Books[i][1]);
existFlag = false;
break;
}
}
if (existFlag) {
client.exception1();
}
} catch (BookNoExistException e) {
System.err.println("图书不存在");
}finally {
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
break;
case 0:
exitFlag = true;
break;
default:
try {
client.exception2();
} catch (InvalidCmdException e) {
// TODO: handle exception
System.out.println("命令输入错误,请根据提示重新输入数字命令");
}
}
if(exitFlag == true) {
input.close();
System.out.println("已退出系统");
break;
}
}
} else {
input.close();
System.out.println("已退出系统");
}
}
public void exception1() throws BookNoExistException {
throw new BookNoExistException("图书不存在");
}
public void exception2() throws InvalidCmdException {
throw new InvalidCmdException("命令输入错误,请根据提示重新输入数字命令");
}
}
Library.java
package views;
public class Library {
public String [][] Books = new String[][] {{"0001","HallyPotter"},{"0002","preference"},{"0003","math"}};
}
InvalidCmdException.java
package views;
public class InvalidCmdException extends Exception {
public InvalidCmdException() {
// TODO Auto-generated constructor stub
}
public InvalidCmdException (String message){
super(message);
}
}
BookNoExistException.java
package views;
public class BookNoExistException extends Exception {
public BookNoExistException() {
// TODO Auto-generated constructor stub
}
public BookNoExistException (String message){
super(message);
}
}