public class Exceptionex1{
private static Scanner console=new Scanner(System.in);
public static void main(String[] args){
String[] books={"汇编","C语言"};
while(true){
System.out.println("输入命令:1-按照名称查找图书; 2-按照序号查找图书");
String book;
try{
int command=inputCommand();
switch(command){
case 1://名称选书
book=getBookByName(books);
System.out.println("book:"+book);
break;
case 2://序号选书
book=getBookByNum(books);
System.out.println("book:"+book);
break;
case -1:
System.out.println("命令输入错误!根据提示输入数字命令!");
continue;
default:
System.out.println("命令输入错误!");
continue;
}
break;
}catch(Exception bne){
System.out.println(bne.getMessage());
continue;
}
}
}
private static String getBookByName(String[] books) throws Exception{
System.out.println("输入图书名称:");
String name=console.next();
for(int i=0;i<books.length;i++){
if(name.equals(books[i]))
return books[i];
}
throw new Exception("图书不存在!");
}
private static String getBookByNum(String[] books) throws Exception{
while(true){
System.out.println("输入图书序号:");
try{
int index=inputCommand();
if(index == -1){
System.out.println("命令输入错误!请根据提示输入数字命令!");
continue;
}
String book=books[index];
return book;
}catch(ArrayIndexOutOfBoundsException e){
Exception bookNotExists= new Exception("图书不存在!");
bookNotExists.initCause(e);
throw bookNotExists;
}
}
}
//从控制台输入命令,用于输入命令和输入图书序号
private static int inputCommand(){
int command;
try{
command = console.nextInt();
return command;
}catch(Exception e){
console=new Scanner(System.in);
return -1;
}
}
}
请大神帮忙指点一下运行过程中选择按书名查找永远只能找到第一本书的名字,其他书名总显示不存在为什么?
慕的地8582982
eq361
相关分类