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

java中的关于处理异常

标签:
Java
package exception;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        //保存图书信息的字符串数组
        String[] books = {"java" , "c语言" ,"高数", "大学英语" , "网页设计"};
        System.out.println("输入命令:1、按照书名查找图书;2、按照序号查找图书");

        while (true) {
            Scanner sc = new Scanner(System.in);
            int number = sc.nextInt();
            String book;
            try{

                switch (number){
                case 1:
                    book = getBooksByName(books);
                    System.out.println("book is :" + book);
                    break;

                case 2:
                    book = getBooksByNumber(books);
                    System.out.println("book is :" + book);
                    break;

                default :
                    System.out.println("命令不存在!请重新输入命令!");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    //通过书名查找图书
    private static String getBooksByName(String[] books) throws Exception{
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入图书名称:");
        String name = sc.next();
        for (int i = 0 ; i < books.length ; i ++ ) {
            if (name.equals(books[i])){
                return books[i];
            }
        }
        throw new Exception ("图书不存在!");
    }

    //通过序号(数组下标)查找图书
    private static String getBooksByNumber(String[] books) throws Exception{
        System.out.println("请输入序号:");
        Scanner sc = new Scanner(System.in);
        if (sc.hasNextInt()){ 
            int num = sc.nextInt();
            return books[num];
        }
        throw new Exception ("图书不存在异常!");

    }
}

小白参考大神的写的~~~~

点击查看更多内容
1人点赞

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

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

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

举报

0/150
提交
取消