import java.util.*;
public class findBook {
private String[] bookName={"高数","英语","C"};
private Scanner input = new Scanner(System.in);
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
findBook bk=new findBook();
while(true){
System.out.println("输入命令:1-按照书名查找图书,2-按照序号查找图书");
try{
int num=bk.getCommond();
switch(num){
case 1:
bk.name();
break;
case 2:
bk.Number();
break;
case -1:
System.out.println("请输入指定的数字");
break;
default:
System.out.println("输入错误!!!");
break;
}
}catch(Exception e){
System.out.println("请重新输入");
continue;
}
}
}
public int getCommond(){
int num;
try{
num=input.nextInt();
return num;
}catch(Exception e){
input.next();
return -1;
}
}
//按照书名查找
public void name() throws Exception{
String strname;
System.out.print("请输入书名:");
//input.nextLine();
strname=input.nextLine(); //如果输入用nextLine的话就无法接收到输入???
for(int i=0;i<3;i++){
if(strname.equals(bookName[i])){
System.out.println("找到了"+strname);
return;
}
}
throw new Exception("图书不存在!");
}
//按照序号查找
public void Number()throws Exception{
while(true){
System.out.println("请输入书号:");
try{
int index=input.nextInt();
System.out.println("找到了"+bookName[index]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("图书不存在");
throw new Exception("BookNotExist");
}catch(Exception e){
System.out.println("输入格式错误,请根据提示输入!!!");
input.next();
continue;
}
}
}
}
http://blog.csdn.net/wjy1090233191/article/details/42080029
这上面有详细解释
问题同上!