import java.util.Scanner;
//命令错误异常
class CommandException extends Exception
{
CommandException(String mis)
{
super(mis);
}
}
//图书不存在异常
class NotExistException extends Exception
{
NotExistException(String mis)
{
super(mis);
}
}
class Books
{
private String[] bookName=new String[]{"论语","高数","数据结构","JAVA编程思想","囚徒健身"};
//按书名查找
public String nameSearch(String name) throws NotExistException
{
for(String str:bookName)
{
if(str.equals(name))
return str;
}
throw new NotExistException("图书不存在!");
}
//按ID查找
public String idSearch(int id) throws NotExistException
{
if(id>bookName.length||id<=0)
throw new NotExistException("图书不存在!");
return bookName[id-1];
}
//运行程序
public void search() throws CommandException,NotExistException
{
Scanner input=new Scanner(System.in);
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int n=input.nextInt();
switch(n)
{
case 1:
System.out.println("输入图书名称:");
System.out.println("book:"+nameSearch(input.next()));
break;
case 2:
System.out.println("输入图书序号:");
System.out.println("book:"+idSearch(input.nextInt()));
break;
default:
throw new CommandException("命令输入错误!请根据提示输入数字命令!");
}
}
}
public class Library
{
public static void main(String[] args) //throws CommandException,NotExistException
{
Books b=new Books();
while(true)
{
try
{
b.search();
}
catch(NotExistException e)
{
System.out.println(e.getMessage());
continue;
}
catch(CommandException e)
{
System.out.println(e.getMessage());
continue;
}
catch(Exception e)
{
System.out.println("命令输入错误!请根据提示输入数字命令!");
continue;
}
break;
}
}
}