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

java中的关于处理异常

四月天_
关注TA
已关注
手记 3
粉丝 2
获赞 12
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 ("图书不存在异常!");

    }
}

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

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP