把int a=input.nextInt();放在Try块外只要开始输入的是字母就报错,但是如果把int a=input.nextInt();放在Try块内一执行就死循环,不知道要怎么改........
package com.imooc;
import java.util.Scanner;
import java.util.InputMismatchException;
public class Test {
public void test1(){
String []books={"高数","数据结构","大学英语","C语言","数电","模电"};
Scanner input=new Scanner(System.in);
int c=1;
do{
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int a=input.nextInt();
try{
if(a!=1&&a!=2){
throw new Exception();
}else if(a==1){
System.out.println("输入图书名称:");
String name=input.next();
try{
for(int i=0;i<books.length;i++){
if(name.equals(books[i])){
System.out.println("book:"+books[i]);
}else if(i<books.length){
continue;
}else{
throw new Exception();
}
}throw new Exception();
}catch(Exception e){
System.out.println("图书不存在!");
}//continue;
}else if(a==2){
System.out.println("输入图书序号:");
try{
int b=input.nextInt();
if(b>=0&&b<=5){
System.out.println("books:"+books[b]);
continue;
}else{
throw new Exception();
}
}catch(InputMismatchException e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
}catch(Exception e){
System.out.println("图书不存在!");
}continue;
}
}catch(Exception e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
}continue;
}while(c==1);
}
}