为了账号安全,请及时绑定邮箱和手机立即绑定

弄了一天,异常真难处理!

package user;


public class Book {

String name;

int number;

public Book(int a,String b) {

this.number=a;

this.name=b;

}


void show() {

System.out.println("图书编号为:"+number+'\n'+"图书名字为:"+name);

}


}

package user;


public class Errora extends Exception {

public Errora(String a) {

super(a);

}

}

package user;


public class Errorb extends Exception {

public Errorb(String b) {

super(b);

}

}

package user;


public class Errorc extends Exception {

public Errorc(String c) {

super(c);

}

}

package user;


import java.util.InputMismatchException;

import java.util.Scanner;


public class Test {

static int d;

static Book[] booklist= {

new Book(1,"金瓶梅"),

new Book(2,"极乐宝鉴"),

new Book(3,"西游记"),

new Book(4,"三国演义"),

new Book(5,"红楼梦"),

new Book(6,"水浒传"),

new Book(7,"如来神掌"),

new Book(8,"周公解梦"),

new Book(9,"山海经")

};

public static void main(String[] args) throws Errora, Errorb, Errorc{

// TODO Auto-generated method stub

System.out.println("请选择查找方式,按序号查找请输入1,按书名查找请输入2");

new Test();

Test.find();


   System.out.println("感谢使用,再见!");

}

public static void find() throws Errora, Errorb, Errorc {

try{

Scanner scanner=new Scanner(System.in);

d=scanner.nextInt();

   new Test().test();

}catch(InputMismatchException e) {

System.out.println("输入参数类型错误,请重新输入!");

new Test().find();

}

}

void test() throws Errora,Errorb,Errorc {

try {

int count = d;

if(count==1) {

System.out.println("请输入查找的序号,回车确认!");

Scanner scanner2=new Scanner(System.in);

int a=scanner2.nextInt();

switch(a) {

case 1:booklist[0].show();break;

case 2:booklist[1].show();break;

case 3:booklist[2].show();break;

case 4:booklist[3].show();break;

case 5:booklist[4].show();break;

case 6:booklist[5].show();break;

case 7:booklist[6].show();break;

case 8:booklist[7].show();break;

case 9:booklist[8].show();break;

default:throw new Errorb("序号不存在!请重新输入!");

}


}

else if(count==2){

System.out.println("请输入查找的书名,回车确认!");

Scanner scanner3=new Scanner(System.in);

String b=scanner3.next();

int num=0;

for(int i=0;i<booklist.length;i++) {

if(b.contentEquals(booklist[i].name)) {

booklist[i].show();

}

else if(!(b.contentEquals(booklist[i].name))) {

num++;

if(num==9) {

throw new Errorc("图书不存在!请重新输入!");

}

}

}

}

else {

throw new Errora("输入错误!请重新输入!");

}

}

catch(Errora e) {

e.printStackTrace();

new Test().find();

}

catch(Errorb e) {

e.printStackTrace();

new Test().test();

}

catch(Errorc e) {

e.printStackTrace();

new Test().test();

}

}

}


正在回答

1 回答

你需要将执行中可能出现异常的代码放到try中执行,如果不知道怎么去捕获异常的话就直接抛出异常,在声明异常的时候如果不知道异常的类型就直接抛出exception.

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Java入门第三季
  • 参与学习       409790    人
  • 解答问题       4340    个

Java中你必须懂得常用技能,不容错过的精彩,快来加入吧

进入课程

弄了一天,异常真难处理!

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信