要求:输入序号和书名查找书籍以及一些异常处理.
思路:善用异常处理就ok
package library;
import java.util.Scanner;
public class librarysystem {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] books= {"thinking in java","安卓探索艺术","c++"};
//Scanner s1=new Scanner(System.in);
System.out.println("***欢迎来到模拟图书系统***");
librarysystem ans=new librarysystem();
ans.find(books);
return ;
}
public void find(String [] books)
{
System.out.println("请输入你的查找方式: 1.按图书序号查找"+" "+"2.按图书名查找");
Scanner s1=new Scanner(System.in);
int x=s1.nextInt();
try{
if(x==1)
{
System.out.println("请输入有效的图书号");
int index=s1.nextInt();
findIndex(books,index);
}
else if(x==2)
{
System.out.println("请输入有效的书名");
String name=s1.next();
findName(books,name);
}
else
{
throw new Exception();
}
}
catch(Exception e)
{
System.out.println("请输入正确的指令");
find(books);
}
return ;
}
public void findIndex(String[] books,int index)
{
try
{
int i=0;
for(;i<books.length;i++)
{
if(i==index)
{
showBook(i,books);
break;
}
}
if(i==books.length)
{
throw new Exception();
}
}
catch(Exception e)
{
System.out.println("图书不存在请重新输入");
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
findIndex(books,x);
}
return ;
}
public void findName(String [] books ,String name)
{
try
{
int i=0;
while(i<books.length)
{
if(books[i].contentEquals(name))
{
showBook(i,books);
break;
}
i++;
}
if(i==books.length)
{
throw new Exception();
}
}
catch(Exception e)
{
System.out.println("图书不存在请重新输入");
Scanner sc=new Scanner(System.in);
String x=sc.next();
findName(books,x);
}
return ;
}
public void showBook(int id,String [] books)
{
System.out.println("你查找的图书:");
System.out.println(books[id]);
System.out.println("是否继续查找:1继续 2:退出");
Scanner s1=new Scanner(System.in);
int x=s1.nextInt();
if(x==1)
{
find(books);
}
else
{
System.exit(0);
}
return ;
}
}