自己编写的尽量用到了,老师课程中所授的内容
欢迎大家交流,错误地方请指正
自定义异常类
package com.kangjia.book;
public class DigitalAcross extends Exception {
public DigitalAcross() {
}
public DigitalAcross(String msg) {
super(msg);
}
}
主要类
package com.kangjia.book;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Book {
static String BookNameSql[] = { "高数", "数据结构" };
public static void main(String[] args) {
// TODO Auto-generated method stub
int Choose = 0;
while (true) {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
Scanner scanner = new Scanner(System.in);
try {
Choose = scanner.nextInt();
even(Choose);
} catch (DigitalAcross e) {
// TODO Auto-generated catch block
System.out.println("您输入的数字不符合要求");
} catch (InputMismatchException e) {
System.out.println("请您输入数字");
}
if (Choose == 1) {
NameQuery();
} else if (Choose == 2) {
NumberQuery();
}
}
}
// 自定义异常,用于判断用户输入的数字是否满足要求
public static void even(int Choose) throws DigitalAcross {
if (Choose > 3 || Choose < 0) {
throw new DigitalAcross("");
}
}
// 图书名称查询
public static void NameQuery() {
System.out.println("请输入图书名称");
Scanner scanner = new Scanner(System.in);
String BookName = scanner.next();
if (Query(BookName)==1) {
System.out.println("图书不存在");
}
}
//图书名称查询辅助循环方法
public static int Query(String BookName){
for (String NameQuery : BookNameSql) {
if (BookName.equals(NameQuery)) {
System.out.println("Book:"+NameQuery);
return 0;
}
}
return 1;
}
// 图书编号进行查询
public static void NumberQuery() {
System.out.println("请输入图书序号");
Scanner scanner = new Scanner(System.in);
int BookNumber = scanner.nextInt();
try {
if (BookNameSql[BookNumber] != null) {
System.out.println("Book:"+BookNameSql[BookNumber]);
System.exit(0);
}
} catch (Exception e) {
System.out.println("图书不存在");
}
}
}