为了账号安全,请及时绑定邮箱和手机立即绑定

利用异常处理编写模拟借书系统程序

标签:
Java 设计
import java.util.*;
class Index {
    static int  flag = 0;
    //定义一个字符串数组存放书籍
    String[] books = new String[]
    {"java编程思想","高等数学","Java疯狂讲义",
    "从你的全世界路过","幻城","大学英语","努力","加油","做自己"};
    //浏览方式选择方法
    public void showEnter() {
        System.out.println("请选择浏览图书的方式:");
        System.out.println("1:按照名称查找"+"\t"+"2:按照序号查找");
        Scanner sc = new Scanner(System.in);
        int choose = sc.nextInt();
        if (choose==1) {
            flag = 1;
            System.out.println("请输入名称");
            dispByName();

        }else if (choose==2) {
            flag = 1;
            System.out.println("请输入序号");

            dispByNum();
        }else {
            System.out.println("输入无效,请按照要求输入!");
            showEnter();
        }   
    }

    //主方法
    public static void main(String[] args) 
    {
        Index ix = new Index();
        while(flag==0) {
            ix.chooseStyle();
        }   
    }
    //判断选择方式的方法
    public void chooseStyle() {
        try {
                showEnter();    
            }
            catch (InputMismatchException e) {
                System.out.println("输入无效,请重新选择浏览方式:");
                chooseStyle();
            }
    }
    //定义一个按照序号显示图书的方法
    public void dispByNum() {       
        Scanner sc = new Scanner(System.in);        
        try{    
            int index = sc.nextInt();
            if (index<=0||index>books.length) {
                throw new Exception();
            }
            System.out.println(books[index-1]);
        }catch(Exception e) {
            System.out.println("请输入合适的序号1-"+books.length);
            dispByNum();
        }       
    }
    //定义一个按照名称显示图书的方法
    public void dispByName() {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        int flag = 0;
        int j = 0;
        try {
            for (int i=0;i<books.length ;i++ ) {
                if (books[i].equals(name)) {                
                    j = i;
                    System.out.println("你好,你查找的图书是第"+(j+1)+"个");
                    flag=1;
                }
            }
            if (flag==0) {
                throw new Exception();
            }
        }catch (Exception e) {
            System.out.println("输入的名字有误,重新输入:");        
            dispByName();
        }   
    }
}
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
3
获赞与收藏
2

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消