老师布置的课后习题,我不按规定的输入整型数字而是输入字符的时候程序陷入死循环怎么解决
主类:
package com.imooc.borrowBook;
import java.util.Scanner;
public class BookManager {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
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){
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 if (num_2>books.length||num_2<=0){
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();
}catch(Exception e){
//e.printStackTrace();
System.out.println("命令输入错误,请按提示输入!!!");
System.out.println();
}
}
}
}
书类:
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);
}
}