package zonghexunlian1;
public class Book {
String name;//书的名称
int number;//书的序号
public Book(String name, int number){
this.name=name;
this.number=number;
}
}
package zonghexunlian1;
public class CaException extends Throwable {//定义的异常类
}
package zonghexunlian1;
public class ErrorNumException extends Throwable {//定义的异常类
}
package zonghexunlian1;
public class NoxhException extends Throwable {//定义的异常类
}
package zonghexunlian1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Initail {
public void cha(){
Initail dy=new Initail();
Book[] book= new Book[]{
new Book("高数", 1),
new Book("数据结构", 2),
new Book("英语", 3)
};
int sr=0;//用来接收输入的数
String sm=null;//用来接收输入的书名
Book nsm=null;//用来接收你选择的书名并赋值,因为赋值的循环遍历是book类所以用book定义
boolean br=false;//定义一个布尔类型的值,用来判断
int xh=0;//用来接收输入的序号
while (sr!=1&&sr!=2){
System.out.println("请输入命令:1-按照书名查找,2-按照序号进行查找");
try {
Scanner input=new Scanner(System.in);
sr=input.nextInt();
if (sr!=1&&sr!=2){
throw new NoxhException();
}
if (sr==1){
System.out.println("请输入图书名称");
sm=input.next();
for (Book bl:book){//数组遍历,用来进行循环比较
if (bl.name.equals(sm)){
br=true;
nsm=bl;
}
}
if (br){
System.out.println("你选择的书是"+nsm.name);
}else {
sr=0;
throw new CaException();
}
}else if (sr==2){
System.out.println("请输入图书序号:");
xh=input.nextInt();
for (Book bl:book){
if (bl.number==xh){
br=true;
nsm=bl;
}
}
if (br){
System.out.println("你要找的书是"+nsm.name);
}else {
sr=0;
throw new ErrorNumException();
}
}
}catch (InputMismatchException e){
System.out.println("你输入错误,请按提示输入数字");
}catch (NoxhException e){
System.out.println("输入有误请输入1或2");
}catch (CaException e){
System.out.println("你输入的图书不存在,请重新输入书名");
}catch (ErrorNumException e){
System.out.println("你输入的序号不存在,请重新输入数字");
}
}
}
public static void main(String[] args) throws NoxhException {
Initail pao=new Initail();
pao.cha();
}
}