ChainCat
2017-12-06 21:10:11浏览 1562
package book;
public class Library {
private String bookName;//书名
private int id;//书的序号
public Library(int id,String bookName){//定义有参构造方法
this.bookName=bookName;
this.id=id;
}
public String getBookName(){//getter访问private修饰的变量
return bookName;
}
public int getId(){
return id;
}
public Library(){}//定义无参构造方法
public void mistake() throws MistakeException{//抛出异常
throw new MistakeException();
}
public void nothingness() throws NothingnessException{
throw new NothingnessException();
}
}
package book;
public class MistakeException extends Exception{//自定义输入指令错误异常
public MistakeException(){}
public MistakeException(String message){
super(message);
}
}
package book;
public class NothingnessException extends Exception{//自定义图书不存在异常
public NothingnessException(){}
public NothingnessException(String message){
super(message);
}
}
package book;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestLibrary {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);//导入包Scanner
Library exception=new Library();//调用无参的构造方法
Library[] books={new Library(1,"计算机基础"),new Library(2,"程序设计基础"),new Library(3,"高等数学"),new Library(4,"大学英语"),new Library(5,"思想与政治")};
for(;;){//使程序循环
try{
System.out.print("输入1用序号查询,输入2用书名查询:");
int select=input.nextInt();
if(select==1){
System.out.println("您使用序号查询~~~");
System.out.print("请输入您要的书的序号:");
try{
int number=input.nextInt();
try{
System.out.println("您要的书是:"+books[number-1].getId()+":"+books[number-1].getBookName());
break;//无异常时结束循环
}catch(ArrayIndexOutOfBoundsException e){//若输入的数大于数组长度,接收数组下标异常
System.out.println("你的序号没有匹配的书!!!");
}
}catch(InputMismatchException e){//若输入的不是整数,接收输入指令不匹配异常
System.out.println("您应该输入整数!");
}
}else if(select==2){
input.nextLine();
System.out.println("您使用书名查询~~~");
System.out.print("请输入书名:");
try{
String c=input.nextLine();
boolean b=false;
for(int i=0;i<books.length;i++){
if(c.equals(books[i].getBookName())){
System.out.println("您要的书是:"+books[i].getId()+":"+books[i].getBookName());
b=true;
}
}if(b) break;
else exception.nothingness();//抛出图书不存在异常
}catch(NothingnessException e){//接收抛出图书不存在异常
System.out.println("你要的书不存在!!!");
}
}else exception.mistake();//抛出输入指令错误异常
}catch(MistakeException e){//接收输入指令错误异常
System.out.println("您输入的指令错误!应该输入1或2~~~");
}catch(InputMismatchException e){
System.out.println("您应该输入整数!");
}
}System.out.println("感谢您的使用!~~~");
}
}