JAVA入門第三季1-9 借書系統手記

at_1發表於2021-09-09

自定異常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 

寫了一晚上。。不容易啊 小白入門努力學習中 希望大佬們多給意見 如何最佳化

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/1817/viewspace-2799188/,如需轉載,請註明出處,否則將追究法律責任。

相關文章