手记

JAVA入门第三季1-9 借书系统手记

自定异常NameException 图书名称异常

package com.book;

public class NameException extends Exception {
    public NameException() {

    }

    public NameException(String message) {
        super(message);

    }
}

自定异常NumException 图书序号异常

package com.book;

public class NumException extends Exception {
    public NumException() {

    }

    public NumException(String message) {
        super(message);

    }
}

Book代码

package com.book;

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

public class Book {
    static Scanner input = new Scanner(System.in);
    static String[] bookname = new String[] { "论语", "C#", "JSP", "HTML", "JAVA" };
    static boolean flag = true;

    public static void main(String[] args) {
        System.out.println("欢迎来到借书系统O~O");
        System.out.println("图书列表:");
        System.out.println("序号" + "\t" + "书名");
        Book bk = new Book();
        int i = 0;
        for (String BK : bookname) {
            System.out.println(i + 1 + "\t" + BK);
            i++;
        }

        while (flag) {
            try {
                System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书!");
                Scanner input = new Scanner(System.in);
                int a = input.nextInt();
                String si = input.nextLine();
                if (a == 1) {
                    try {
                        bk.ex1();
                        flag = false;
                    } catch (NameException e) {
                        System.out.println(e.getMessage());
                    }
                } else if (a == 2) {
                    try {
                        bk.ex2();
                        flag = false;
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                } else {
                    System.out.println("序号输入错误!");
                }
            } catch (InputMismatchException e) {
                System.out.println("命令输入错误!请根据提示输入数字命令!");

            }
        }
    }

    public void ex1() throws NameException {
        System.out.println("输入图书名称:");
        String b = Book.input.next();
        boolean p = false;
        for (String bb : bookname) {
            if (b.equals(bb)) {
                p = true;
            }
        }
        if (p) {
            System.out.println("book:" + b);
        } else {
            throw new NameException("图书不存在!");
        }
    }

    public void ex2() throws NumException {
        System.out.println("输入图书序号:");
        int c = Book.input.nextInt();

        if (c >= 1 && c <= bookname.length) {
            System.out.println("book:" + bookname[c - 1]);
        } else {
            throw new NumException("图书不存在!");

        }
    }

}

写了一晚上。。不容易啊 小白入门努力学习中 希望大佬们多给意见 如何优化

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

热门评论

你好,虽然实现了借书功能,但是每输错一次就重新运行下,"输入命令:1-按照名称查找图书;2-按照序号查找图书!"
而老师视频中,输错图书序号可以再次重新输入序号,不必再输入命令

图片上传不了

查看全部评论