第一步先定义两个异常。
/*
* 该异常用于输入图书名称,但图书库里并无此书
*/
public class notbookException extends Exception {
public notbookException(){
}
public notbookException(String message){
super(message);
}
}
/*
该异常用于虽然输入的是INT变量,但不是1或2
*/
public class notnumberException extends Exception {
public notnumberException(){
}
public notnumberException(String message){
super(message);
}
}
接下来需要抛出这两个异常,并抓住异常,把异常包装成新的异常并抛出,方便在程序中调用!
/*
*抛出notbookException异常!
*/
public void test() throws notbookException{
throw new notbookException();
}
/*
* 调用test()方法
*抓住test()方法抛出的notbookException异常!
*把notbookException异常包装成RuntimeException异常并抛出!
*/
public void test2() {
try{
test();
}catch(notbookException e){
RuntimeException newExc=new RuntimeException();
throw newExc;
}
}
/*
*抛出notnumberException异常!
*/
public void test3() throws notnumberException{
throw new notnumberException();
}
/*
* 调用test3()方法
*抓住test3()方法抛出的notnumberException异常!
*把notnumberException异常包装成RuntimeException异常并抛出!
*/
public void test4(){
try{
test3();
}catch(notnumberException e){
InputMismatchException newExc=new InputMismatchException();
throw newExc;
}
}
接下来要定义个个String类型的数组,里面存着各式各样的书!
static String[] book=new String[]{"恶魔法则","星辰变","佛本是道","庆余年","斗破苍穹","流氓高手","陈二狗的妖孽人生","神墓","紫川","无限恐怖",
"坏蛋是怎样炼成的","盘龙","亵渎","邪气凛然","阳神","飘渺之旅","小兵传奇","盗墓笔记"};
创建该系统的运行方法方便在main方法中调用!
public void run(){
Scanner input =new Scanner(System.in);
try{
System.out.println("输入命令:1-按照书名查找图书;2-按照序号查找图书");
int input1=input.nextInt();
if(input1==1){
System.out.println("输入图书名称");
String input2=input.next();
boolean flag=false;
for(int i=0;i<book.length;i++){
if(input2.equals(book[i])){
flag=true;
break;
}
else flag=false;
}
if(flag==true){
System.out.println("BOOK:"+input2);
}
else if(flag==false){
test2();
}
}
else if(input1==2){
System.out.println("请输入图书序号!");
int input3=input.nextInt();
System.out.println("BOOK:"+book[input3-1]);
}
else
test4();
}catch(InputMismatchException e){
System.out.println("命令输入错误!请根据提示输入数据命令!");
InputMismatchException newExc=new InputMismatchException();
newExc.initCause(e);
throw newExc;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("图书不存在!");
ArrayIndexOutOfBoundsException newExc=new ArrayIndexOutOfBoundsException();
newExc.initCause(e);
throw newExc;
}catch(RuntimeException e){
System.out.println("图书不存在!");
RuntimeException newExc=new RuntimeException();
newExc.initCause(e);
//k=3;
//return k;
throw newExc;
}catch(Exception e){
System.out.println("不知名异常!");
RuntimeException newExc=new RuntimeException();
newExc.initCause(e);
//k=4;
//return k;
throw newExc;
}
}
main 方法!
public static void main(String[] args){
borrowbook newbwb=new borrowbook();
//boolean flag=true;
while(true){
try{
newbwb.run();
}catch(Exception e){
continue;
}
break;
}
}
热门评论
同学,这代码有点问题:else与上一个if对应,所以input1不为2的时候,都会走test4,所以按名称正常输出时有正常输出,但是会报错,把else test4();加个判断input1 != 1的条件吧。