手记

Java入门第三季-异常-图书馆借书系统

参考大神的代码,实现循环查询读书,

  1. 名称输入异常类定义
    NameException.java
package com.imooc;
/**
 * 书名异常类
 * @author Majinglian
 *
 */
public class NameException extends Exception{

    public NameException() {

    }
    public NameException(String message) {
        super(message);
    }
}
  1. 数字输入异常类定义
    NumException.java

    package com.imooc;
    /**
    * 序号异常类
    * @author Majinglian
    *
    */
    public class NumException extends Exception{
    public NumException() {
    
    }
    
    public NumException(String message) {
        super(message);
    }   
    }
  2. 具体实现类
    BookTest .java
    
    package com.imooc;

import java.util.Scanner;

import com.imooc.NameException;
import com.imooc.NumException;

public class BookTest {
private static Scanner scanner;
static String[] bookInfo = {"阿甘正传", "西游记", "红楼梦"};
static BookTest bt = new BookTest();
public static void main(String[] args) {
bt.search();
}

public void search() {
    System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
    try {
        scanner = new Scanner(System.in);
        int input = scanner.nextInt();
        if(input == 1){
            try {
                 bt.nameSearch();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

        }else if(input == 2){
            try {
                bt.numSearch();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }else {
            System.out.println("命令输入错误,请根据提示输入数字命令");
        }
    } catch (Exception e) {
        System.out.println("命令输入错误,请根据提示输入数字命令");
    }   
      search();

}

public void nameSearch() throws NameException {
    System.out.println("输入图书名称:");
    String inputName = scanner.next();
    boolean flag = false;
    for (String book : bookInfo) {
        if (book.equals(inputName)) {
            flag = true;
        }
    }   
    if (flag) {
        System.out.println("book:" + inputName);
    } else {
        throw new NameException("图书不存在");
    }
}

public void numSearch() throws NumException {
    System.out.println("输入图书序号:");
    int num = scanner.nextInt();
   if (num >= 1 && num <= bookInfo.length) {
      System.out.println("book:"+ bookInfo[num-1]);
    } else {
      throw new NumException("图书不存在");
    }       
}

}

1人推荐
随时随地看视频
慕课网APP