问答详情
源自:1-9 经验总结

【交作业啦】


//自定义异常1:命令错误异常

package com.imooc.exceptionTest;

public class wrongCommandException extends Exception {

      public wrongCommandException() {

   }


      public wrongCommandException(String message) {

      super(message);

   }

}

//自定义异常2:图书不存在异常

package com.imooc.exceptionTest;

public class wrongNameException extends Exception {

      public wrongNameException() {

   }

      public wrongNameException(String message) {

      super(message);

   }

}

//测试类

package com.imooc.exceptionTest;

import java.util.Arrays;

import java.util.Scanner;

 

public class BorrowE {

   public static void main(String[] args) {

      BorrowE borrow = new BorrowE();

      borrow.select();

   }

   public void select() {

      String[] books = new String[] {"数据结构","Java从入门到精通","计算机网络","操作系统","数字图像处理"};

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

      Scanner input = new Scanner(System.in);

      try{

        if(input.hasNextInt()) {

           int in = input.nextInt();

           if(in==1) {

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

              Scanner input2 = new Scanner(System.in);

              String inM = input2.nextLine();

              boolean flag = Arrays.asList(books).contains(inM);

              if(flag) {

                 System.out.println(inM+"存在!");

              }else {

                 throw new wrongNameException();

              }

           }else if(in==2) {

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

              int inN = input.nextInt();

              if(inN>=0 && inN<books.length) {

                 System.out.println("你要查询的图书名称为:"+books[inN]);

              }else {

                 throw new wrongNameException();

              }

           }else {

              throw new wrongCommandException();

           }

        }else {

           throw new wrongCommandException();

        }

      }catch(wrongCommandException e){

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

        select();

      }catch(wrongNameException e) {

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

        select();

      }

   }


}


提问者:洋阳羊Y 2019-02-21 16:31

个回答

  • qq_真夜_1
    2019-03-18 20:34:37

    有点问题,第二个输序号的地方之前也需要if(input.hasNextInt()) 判断是否为整数输入

  • qq_真夜_1
    2019-03-18 16:01:29

    琢磨半天视频不如看这一篇作业,多谢

  • 点点鬼
    2019-02-27 15:48:34

    写得很清晰,看完基本就明白了思路,谢谢!