tppe
大概方式:1、判断用户输入的类型是否正确,不正确捕获异常,把他包装成我自己定义的异常2、判断用户输入的数是多少2.1、如果是1,则打印“输入图书名称”,用户输入,定义一个Book类型的数组,然后遍历,定义一个计数器count,如果用户输入的值等于数组遍历的值(书的名字不能重复,此处有错误,因为如果名字重复的话,输入名字应该同时出现重复的书名和不同的书号(自动默认书号是不能重复的)),计数器加1,这里如果计数器不等于1的话(有两个原因:(1)大于1:可能是出现了重复的书名 (2)等于0:可能是不存在这本书 (3)小于0:不知道了。。。),但是我这边是不管是哪种原因,我都是用的“图书不存在”这个异常,所以也有问题2.2、如果是2:同上整个有点混乱,还有好多问题1、package com.library;public class Book {private String bookName;private int lNum;public Book() {super();// TODO Auto-generated constructor stub}public Book(String bookName, int num) {super();this.bookName = bookName;lNum = num;}public String getBookName() {return bookName;}public int getLNum() {return lNum;}}2、package com.library;public class MyException extends Exception{public MyException(){}public MyException(String message){super(message);}}3、package com.library;import java.util.Scanner;public class TestLibrary {private static TestLibrary tl;public static void main(String[] args) {tl = new TestLibrary();System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");try {tl.test2();} catch (MyException e) {// TODO Auto-generated catch blocke.printStackTrace();for(int i = 1; i != 0; i++){System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");try {tl.test2();} catch (MyException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}} public void test2() throws MyException{Book book1 = new Book("数据结构",1);Book book2 = new Book("高数",2);//Book book3 = new Book("高数",3);Book[] library = {book1,book2};try {Scanner s = new Scanner(System.in);Integer input = s.nextInt();if((input instanceof Integer) == true){ if(input.equals(1)){int count = 0;System.out.println("输入图书名称");Scanner s1 = new Scanner(System.in);String bookName = s1.nextLine();for(int i = 0; i < library.length; i++){if(bookName.equals(library[i].getBookName())){System.out.println("book:" + library[i].getBookName());count++;//System.out.println(count+"...");}} if(count != 1){tl.test4();}}else if(input.equals(2)){int count = 0;System.out.println("输入图书序号");Scanner s2 = new Scanner(System.in);int lNum = s2.nextInt();for(int i = 0; i < library.length; i++){if(lNum == (library[i].getLNum())){System.out.println("book:" + library[i].getBookName());count++;}}if(count != 1){tl.test4();}}}} catch (Exception e){MyException exception = new MyException("命令输入错误!请根据提示输入数字命令");exception.initCause(e);throw exception;}} // public void test1() throws MyException { throw new MyException("命令输入错误!请根据提示输入数字命令");// } public void test3() throws MyException{ throw new MyException("图书不存在");} public void test4(){try {test3();} catch (MyException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}