我写的事例,欢迎讨论
package com.exception;
import java.util.*;
public class Test {
String[] book = {"高数","英语","语文","数据","java"};
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int receive = scanner.nextInt();
Test test = new Test();
try {
switch(receive) {
case 1:
test.book();
break;
case 2:
test.num();
break;
default:
throw new NoBookException("命令输入错误!请根据提示输入数子命令!");
}
}catch(NoBookException e) {
e.printStackTrace();
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
}
}
public void book() throws NoBookException{
System.out.println("输入图书名称:");
Scanner sb = new Scanner(System.in);
String name = sb.next();
boolean flag = false;
for(String bk:book) {
if(name.equals(bk)) {
flag = true;
break;
}
}
if(flag) {
System.out.println("book:"+name);
}else {
throw new NoBookException("图书不存在!");
}
}
public void num() throws NoBookException{
System.out.println("输入图书序号:");
Scanner sn = new Scanner(System.in);
int i = sn.nextInt();
String str = book[i-1];
if(str == null || str.equals("")) {
throw new NoBookException("图书不存在!");
}else {
System.out.println("book:"+str);
}
}
}