交作业了啊啊啊啊
import java.util.Arrays; import java.util.Scanner; public class BorrowBook { public static void main(String[] args) { // TODO Auto-generated method stub BorrowBook book = new BorrowBook(); book.Select(); } public void Select() { String[] books = new String[] {"java基础","水浒传","红楼梦","西游记","数据结构"}; System.out.println("输入命令:1-按照名称查找图书; 2-按照序号查找图书\""); Scanner input = new Scanner(System.in); int num = input.nextInt(); try { if(num == 1) { System.out.println("请输入图书名称:"); Scanner input1 = new Scanner(System.in); String name = input1.nextLine(); boolean ture = Arrays.asList(books).contains(name); if(ture) { System.out.println("您输入的"+ name +"存在"); }else { throw new NoBookExecption(); } }else if(num == 2) { System.out.println("请输入图书序列号:"); Scanner input2 = new Scanner(System.in); int xuhao = input2.nextInt(); if(xuhao>=0 && xuhao<books.length) { System.out.println("您要查询的图书名称为"+books[xuhao-1]); }else { throw new CommandExecption(); } } }catch(CommandExecption e){ System.out.println("你输入的命令有误!请检查后重新输入:"); Select(); }catch(NoBookExecption e) { System.out.println("图书不存在!请重新输入你要查询的名称:"); Select(); } } }
自定义异常类 CommandExecption类(命令输入有误)
public class CommandExecption extends Exception{ public CommandExecption() {//无参方法 } public CommandExecption(String message) {//有参方法 super(message); } }
自定义异常类
//图书不存在异常
public class NoBookExecption extends Exception{ public NoBookExecption() {//无参方法 } public NoBookExecption(String message) {//有参方法 super(message); } }