---------------------------------------------------------------------
//自定义的异常
public class ErrorMinException extends Exception{
public ErrorMinException() {
System.out.println("命令输入错误!请按提示输入数字命令!");
}
}
--------------------------------------------------------------------
//自定义的异常
public class BookDoesNotExistException extends Exception{
public BookDoesNotExistException() {
System.out.println("图书不存在!");
}
}
------------------------------------------------------------------------
//主要的东西
import java.util.Scanner;
public class BookTest {
//主方法里就定义了一个数组,然后是选择怎样找书的方法
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] Books = {"c","c++","java","python","js"};
select(Books);
}
//决定怎样找书的方法
public static void select(String[] Books) {
Scanner scan = new Scanner(System.in);
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
try {
int a = scan.nextInt();//如果输入的为字母,则catch
if(a == 1) {
findByName(Books);//调用名字查找方法
}else if(a == 2) {
findByNum(Books);//调用序号查找方法
}else {
System.out.println("命令输入错误!请按提示输入数字命令!");//如果输入的为不符合要求的数字
select(Books);//则跳转回来
}
}catch(Exception e) {
new ErrorMinException();//定义的异常
select(Books);//跳转回来
}
scan.close();
}
//名字查找的方法
public static void findByName(String[] Books) {
System.out.println("请输入图书名称:");
Scanner scan = new Scanner(System.in);
String name = scan.next();
int flag = 0;//判断是否存在
for(String book : Books) {
if(book.equals(name)) {
System.out.println("book:" + name);
flag = 1;//如果存在,则flag = 1;
}
}
if(flag == 0) {
System.out.println("图书不存在!");//如果flag 任然等于0则不存在
select(Books);//跳转
}
scan.close();
}
public static void findByNum(String[] Books) {
System.out.println("请输入图书序号:");
Scanner scan = new Scanner(System.in);
try {
int num = scan.nextInt();//如果输入的不是int型,则catch
System.out.println("book:" + Books[num]);//如果数组越界,则catch
}catch(Exception e) {
new BookDoesNotExistException();
select(Books);//跳转
}
scan.close();
}
}