老师布置的课后习题,for循环中在条件满足的情况下没有执行if,只执行了else
Book类
package com.imooc.borrowBook;
public class Book {
public String bookName;
public int bookNum;
public Book(String bookName,int bookNum){
this.bookName = bookName;
this.bookNum = bookNum;
}
}
自定义异常类
package com.imooc.borrowBook;
public class NoExistException extends Exception {
public NoExistException(){
}
public NoExistException(String message){
super(message);
}
}
主类
package com.imooc.borrowBook;
import java.util.Scanner;
public class BookManager {
public static void main(String[] args) {
// TODO Auto-generated method stub
Book books[] = {new Book("高数",1),new Book("JavaEE",2),new Book("Html5",3),
new Book("数据结构",4),new Book("C++",5),new Book("操作系统",6)};
while(true){
Scanner in = new Scanner(System.in);
System.out.println("请选择查找方式:");
System.out.println("1.按书名查找图书 2.按序号查找图书 3.退出");
try{
int num = in.nextInt();
if(num==1){
System.out.println("请输入书名:");
String num_1 = in.next();
//boolean name = false;
for(int i=0;i<books.length;i++){
if(num_1.equals(books[i].bookName)){
System.out.println("book:"+books[i].bookName);
//name = true;
}else{
throw new NoExistException();
}
}
}else if(num==2){
System.out.println("请输入书的序号:");
int num_2 = in.nextInt();
//boolean number = false;
for(int i=0;i<books.length;i++){
if(num_2 == books[i].bookNum){
System.out.println("book:"+books[i].bookName);
//number = true;
}else
throw new NoExistException();
}
}else if(num==3){
System.out.println("欢迎下次再来!");
System.exit(0);
}else
throw new Exception();
//System.out.println("命令输入错误,请按提示输入!!!");
}
catch(NoExistException e){
//e.printStackTrace();
System.out.println("该图书不存在!");
System.out.println(); continue;
}catch(Exception e){
//e.printStackTrace();
System.out.println("命令输入错误,请按提示输入!!!");
System.out.println();
in.nextLine();//清空缓存区的中的数据
}
}
}
}
问题如下:
当我输入正确的序号或者书名时,程序没有执行循环中的if(条件满足的情况下),而是直接执行的else 报出异常,不知道怎么解决,请帮我解决下,感激不尽!!