手记

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人推荐
随时随地看视频
慕课网APP