问答详情
源自:1-9 经验总结

为什么输入存在的图书名也是执行异常?求大蛇指点

public class borrowBooks {


public static void main(String[] args) {

// 调用select方法

borrowBooks Select = new borrowBooks();

Select.select();

}

/**

*/

public void select() {

String[][] bookList=new String[][] {{"1","水浒传"},{"2","红楼梦"},{"3","三国演义"}};

//String[] bookList = new String[] {"java基础","水浒传","红楼梦","西游记","数据结构"}; 

System.out.println("输入命令:1-按照图书名称查询   2-按照图书编号查询");

Scanner input = new Scanner(System.in);

int num = input.nextInt();

try {

if(num==1) {

System.out.println("请输入您要查找的图书名称:");

Scanner input1 = new Scanner(System.in);

String bookName=input1.nextLine();

//一维数组

/* boolean t=Arrays.asList(bookList).contains(bookName);

if(t) {

System.out.println("您输入的图书"+bookName+"存在!");

}else {

throw new NobookException();

}*/

//二维数组

for(String[] bookname:bookList) {

for(String book:bookname) {

if(book.equals(bookName)) {

System.out.println("您输入的图书"+book+"存在!");

}else  {

throw new NobookException();

}

}

}

}else if(num==2) {

System.out.println("请输入您要查找的图书编号");

Scanner input2 = new Scanner(System.in);

int bookNum=input2.nextInt();

if(bookNum>=1&&bookNum<=bookList.length) {

System.out.println("您查找的图书名称为"+bookList[bookNum-1]);

}else {

throw new NobookException();

}

}else {

throw new CommandException();

}

}catch (NobookException e) {

// TODO: handle exception

System.out.println("您输入的图书不存在!请重新输入");

select();

}catch (CommandException e) {

// TODO: handle exception

System.out.println("您输入的命令有误,请重新输入");

select();

}

}

}


提问者:Jenny李 2019-03-17 17:48

个回答

  • xinzhongdexingxing
    2019-03-18 06:17:39

    以下语句执行多次,书名不一样时,就抛出异常。

    if(book.equals(bookName)) {

    System.out.println("您输入的图书"+book+"存在!");

    }else  {

    throw new NobookException();

    }