Java教程

JAVA模拟图书查询

本文主要是介绍JAVA模拟图书查询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package bookstroe.test;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Bookstore {
    String[] book = {"java", "高数", "C++", "python"};
    int flag = 0;

    public static void main(String[] args) {
        Bookstore bs = new Bookstore();
            bs.select();
    }

    public void select() {
        Scanner input =new Scanner(System.in);
            try {
                System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书\n");
                int chose = input.nextInt();
                if (chose != 1 && chose != 2) {
                    throw new InputException();
                } else if (chose == 1) {
                    System.out.println("输入图书名称:");
                    String name = input.next();
                    selectName(name);
                    select();
                } else {
                    System.out.println("输入图书序号:");
                    int number = input.nextInt();
                    selectNumber(number);
                    select();
                }
            } catch (InputException | InputMismatchException e) {
                System.out.println("命令输入错误!请根据提示输入数字命令\n");
                select();
            } catch (NameNotFoundException | ArrayIndexOutOfBoundsException e) {
                System.out.println("图书不存在!\n");
                select();
            }catch (Exception e){
                e.printStackTrace();
            }
    }

    public void selectName(String name) throws NameNotFoundException {
        for (String s : book) {
            if (s.equals(name)) {
                System.out.println("book:" + name);
                flag = 1;
            }
        }
        if (flag == 0) throw new NameNotFoundException();
    }

    public void selectNumber(int number) {
        System.out.println("book:" + book[number]);
    }
}
package bookstroe.test;

public class NameNotFoundException extends Exception{
    public NameNotFoundException(){

    }
    public NameNotFoundException(String message){
        super(message);
    }

}
package bookstroe.test;

public class InputException extends Exception{
    InputException(){

    }
    InputException(String message){
        super(message);
    }
}


这篇关于JAVA模拟图书查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!