继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

java入门第三季第一章作业--模拟借书系统

慕粉1054143596
关注TA
已关注
手记 2
粉丝 0
获赞 4
package com.lendbook;
import java.util.Scanner;

public class LendBook {
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String books[] = { "C语言", "数据结构", "高数", "英语", "毛概" };

        while (true) {
            System.out.println("输入命令:1-按照书名查找图书;2-按照序号查找图书");
            String book;
            try {
                int command = inputCommand();
                switch (command) {
                case 1:
                    book = getBookByName(books);
                    System.out.println("book:" + book);
                    break;
                case 2:
                    book = getBookByNumber(books);
                    System.out.println("book:" + book);
                    break;
                case -1:
                    System.out.println("输入有错!请根据提示重新输入!");
                    continue;
                default:
                    System.out.println("命令输入错误!");
                    continue;
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                continue;
            }
        }
    }

    private static String getBookByName(String[] books) throws Exception {
        System.out.println("输入图书名称:");
        String name=scanner.nextLine();
        for(String book:books){
            if(book.equals(name))
                return book;
        }
        throw new Exception("图书不存在!");
    }

    private static String getBookByNumber(String[] books) throws Exception{
        while(true){
            System.out.println("输入图书序号:");
            try{
                int index=inputCommand();
                if(index==-1){
                    System.out.println("输入有错!请根据提示重新输入!");
                    continue;
                }
                String book=books[index];
                return book;
            }catch(ArrayIndexOutOfBoundsException e){
                 Exception bookNotExist=new Exception("图书不存在!");
                 bookNotExist.initCause(e);
                 throw bookNotExist;
            }           
        }
    }

    private static int inputCommand() {
        int command;
        try {
            command = Integer.parseInt(scanner.nextLine());
            return command;
        } catch (Exception e) {
            return -1;
        }
    }
}
打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP