public class Borrow { public static void main(String[] args) throws CommandException, NoResultException { Borrow borrow = new Borrow(); borrow.select(); } public void select() throws CommandException, NoResultException { String[] books = {"西游记", "红楼梦", "水浒传", "三国演义"}; Scanner input = new Scanner(System.in); try { System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); int ipt1 = input.nextInt(); if (ipt1 == 1) { System.out.println("输入图书名称:"); String ipt2 = input.next(); String result = ""; for (String book : books) { if (ipt2.contentEquals(book)) { result = book; } } if (result != "") { System.out.println("book:" + result); } else { throw new NoResultException("图书不存在!"); } } else if (ipt1 == 2) { System.out.println("输入图书序号:"); int ipt3 = input.nextInt(); if (ipt3 > books.length || ipt3 <= 0) { throw new NoResultException("图书不存在!"); } else if (ipt3 > 0 && ipt3 <= books.length) { System.out.println("book:" + books[ipt3 - 1]); } else { throw new CommandException("命令输入错误!请根据提示输入数字命令!"); } } else { throw new CommandException("命令输入错误!请根据提示输入数字命令!"); } } catch (CommandException e) { System.out.println(e.getMessage()); select(); } catch (NoResultException e) { System.out.println(e.getMessage()); select(); } catch (InputMismatchException e) { System.out.println("命令输入错误!请根据提示输入数字命令!"); select(); } } } public class CommandException extends Exception { public CommandException() { } public CommandException(String e) { super(e); } } public class NoResultException extends Exception { public NoResultException() { } public NoResultException(String e) { super(e); } }
1.你在主方法里声明抛出异常,就是JVM来处理异常了,写不写都是一样,出现异常都会报错。
2.这个问题无关紧要,就是select方法里没有声明会抛出InputMismatchException异常
3.怎么连把代码连同格式一起粘贴上去?我知道可以选代码语言,但是选择Java后我复制的代码不会自动换行,只能我自己手动一行一行按回车换行。
稍作调整可以正常运行