问答详情
源自:1-2 Java中使用try..catch..finally实现异常处理

交作业。。

package practise;

import java.util.InputMismatchException;

import java.util.Scanner;


public class BorrowBook {

    public static void main(String[] args) {

        BorrowBook borrowBook=new BorrowBook();

        borrowBook.borrow();

    }

    public void borrow() {

        System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");

        Scanner sc1=new Scanner(System.in);

        try {

            int num=sc1.nextInt();

            if(num==1) {

            bookname();

            }else if(num==2) {

            booknum();

            }

            sc1.close();

        }catch(Exception e) {

            System.out.println("命令输入错误,请根据提示输入数字命令!");

            borrow();

        }

    }

    public void bookname(){

        String[] books= {"高数","数据结构"};

        System.out.println("输入图书名称:");

        Scanner sc1=new Scanner(System.in);

        String str1=sc1.nextLine();

        try {

            for(int i=0;i<=books.length;i++) {

                if(books[i].equals(str1)) {

                    System.out.println("book:"+str1);

                    break;

                }

            }

        }catch(Exception e) {

            System.out.println("图书不存在!");

            borrow();

        }

        sc1.close();

    }

    public void booknum() {

        String[] books= {"高数","数据结构"};

        System.out.println("输入图书序号:");

        Scanner sc1=new Scanner(System.in);

        try {

            int num=sc1.nextInt();

            System.out.println("book:"+books[num-1]);

        }catch(InputMismatchException e) {

            System.out.println("命令输入错误,请根据提示输入数字命令!");

            booknum();

        }catch(Exception e) {

            System.out.println("图书不存在!");

            borrow();

        }

        sc1.close();


}

}




提问者:weixin_慕粉7554262 2019-07-17 17:06

个回答

  • qq_慕数据533744
    2019-07-22 20:33:15

    你只是捕获异常 却没有抛出异常