手记

Java入门第三季-异常处理·模拟借书系统的实现

Java入门第三季的异常处理的练习。
感觉不应该做死去反复使用匿名类啊。
然后就是java里面如何判断输入的是哪种类型?正则表达式有点不太懂咯。

    // BookSys类:
    package com.bob;

    public class BookSys {
        String[] bookName = { "数据结构", "高等数学", "中国近现代史纲要", "数字电路" };
    }
    // BookSearch类:
    package com.bob;

    import java.util.Scanner;

    public class BookSearch {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("欢迎使用图书查询系统!");
            enterSys();
        }

        public static void enterSys() {
            System.out.println("请输入您要查询的书名或书号:");
            BookSearch bs = new BookSearch();
            bs.bookSearch();
            System.out.println("查询完毕,请问您还需要继续查询吗?(Y/N)");
            Scanner d = new Scanner(System.in);
            String f = d.next();
            if (f.equals("Y")) {
                enterSys();
            } else {
                System.out.println("谢谢使用,再见!");
                return;
            }
        }

        public void bookSearch() {
            Scanner c = new Scanner(System.in);
            String input = c.next();
            if (input.matches("(\\d+)(\\d*.\\d+)(\\d+.\\d*)")) {
                System.out.println("您选择的是序号查询");
                try {
                    checkByNum(Integer.parseInt(input));
                } catch (NumberFormatException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                System.out.println("您选择的是按照书名查询");
                try {
                    checkByName(input);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        public void checkByNum(int number) throws Exception {
            if (number <= new BookSys().bookName.length)
                System.out.println("您查找的书为" + "《" + new BookSys().bookName[number - 1] + "》");
            else {
                System.out.println("您输入的序号有误,请重新输入!");
                enterSys();
            }
        }

        public void checkByName(String name) throws Exception {
            int i;
            for (i = 0; i < new BookSys().bookName.length; i++) {
                if (new BookSys().bookName[i].equals(name)) {
                    break;
                }
            }
            if (i < new BookSys().bookName.length) {
                System.out.println("您查找的书为" + "《" + name + "》," + "是第" + (i + 1) + "号图书!");
            } else
                System.out.println("没有这本图书!");
        }
    }
1人推荐
随时随地看视频
慕课网APP