首页 > IT职业 > IT生活 > JAVA入门第三季第一章第九节课后练习题!
第一步先定义两个异常。
/*
* 该异常用于输入图书名称,但图书库里并无此书
*/
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 main 方法!
public static void main(String[] args){
borrowbook newbwb=new borrowbook();
//boolean flag=true;
while(true){
try{
newbwb.run();
}catch(Exception e){
continue;
}
break;
}
} 来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3016/viewspace-2798320/ ,如需转载,请注明出处,否则将追究法律责任。