手记

java第三季1-9_查书系统

package yichang03;
import java.util.*;

public class RentBook {

/**
 * 图书查找系统
 * 用户输入「书名」或「序列号」来检索
 * a.检索命令错误,"异常:无效的数字,请根据提示输入1或2,请重输!"
 * b.「书名」不存在的场合、"异常:图书不存在,请重输!"
 * c.「序列号」不存在的场合、"异常:图书不存在,请重输!"
 */

//数组_书名
String[] bookList = new String[]{"名侦探柯南","One Picec","Dragon Ball","西游记"};

//输入对象实例化
Scanner scan = new Scanner(System.in);

//查书系统开始
public void Start(){

    try{
        Scanner scan = new Scanner(System.in);
        System.out.println("请输: 1-按书名来检索; 2-按序列号来检索");
        int i = scan.nextInt();
        if(i == 1){

            //按书名来检索
            SearchName();
        }
        else if(i ==2){

            //按序列号来检索
            SearchNumber();     
        }
        else
            throw new UnvalidNumberException("异常:无效的数字,请根据提示输入1或2,请重输!");
    }catch(UnvalidNumberException une){
        System.out.println(une.getMessage());
        Start();
    }catch(InputMismatchException ime){
        System.out.println("异常:操作无效,请根据提示重新输入。");
        Start();
    }catch(BookException be){
        System.out.println(be.getMessage());
        Start();
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
}

//书名检索方法、如果发生异常抛出,从Start()方法重新执行
public void SearchName() throws BookException{

        System.out.println("请输入书名:");
        String bookName = scan.nextLine();
        boolean bookCheck = false; 

        for(int i = 0; i < bookList.length; i++){
            if(bookName.equals(bookList[i])){
                System.out.println("book:" + bookName);
                bookCheck = true;
            }
        }
        if(bookCheck != true){
            throw new BookException("异常:图书不存在,请重输!");
        }
}

//序列号检索方法、如果发生异常、1.输入不存在的序列号、抛出异常并从Start()方法重新执行;2.输入无效文字,抛出异常并重新输入序列号
public void SearchNumber() throws BookException{

    try{
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入序列号:");
        int i = scan.nextInt();

        if(i >= 1 && i <=4){
            System.out.println("book:" + bookList[i - 1]);
        }
        else
            throw new BookException("异常:图书不存在,请重输!");
    }catch(InputMismatchException ime){
        System.out.println("异常:无效文字,请根据提示重新输入。");
        SearchNumber();
    }
}

//main
public static void main(String[] args){
    // TODO Auto-generated method stub
    RentBook rentBook = new RentBook();

    rentBook.Start();

    System.out.println("谢谢使用!");

}

}
public class BookException extends Exception {

public BookException(String str){
    super(str);
}

}
public class UnvalidNumberException extends Exception {

public UnvalidNumberException(String str){
    super(str);
}

}

1人推荐
随时随地看视频
慕课网APP