public class Book {
private int id =0;
private String name = null;
public int getId() {
return id;
}
public String getName() {
return name;
}
//Book构造方法
public Book(int ID,String NAME){
this.id =ID;
this.name =NAME;
}
//toString 方法
public String toString(){
return "ID:"+id +"\t书名" + name ;
}
}
public class MyException extends Exception {
//自定义异常类
String message;
public MyException(String EMessage){
message =EMessage;
}
public String getMessage() {
return message;
}
}
import java.util.Scanner;
public class Test {
//创建对象与array数组
static Book b1 =new Book(1,"书1");
static Book b2 =new Book(2,"书2");
static Book b3 =new Book(3,"书3");
static Book[] array =new Book[]{b1,b2,b3};
//判断查找方式(input1())
public static int input1() throws MyException{
System.out.println("请输入数字命令:");
System.out.println("1-按照书名查找图书\t2-按照序号查找图书");
Scanner input1 =new Scanner(System.in);
int in1 =input1.nextInt();
if(in1!=1 && in1!=2){
throw new MyException("错误命令异常");
}
return in1;
}
//通过书名
public static String input2() throws MyException{
System.out.println("请输入书名:");
Scanner input2 =new Scanner(System.in);
String in2 =input2.nextLine();
//创建新字符串数组
String[] n =new String[3];
boolean torf =true;
//循环遍历数组,新数组与array对比,判断书是否存在
for(int i =0;i<array.length;i++){
n[i]=array[i].getName();
if(n[i].equals(in2)==true){
torf =false;
}else if(i ==array.length-1){
System.out.println(array[i].toString());
}
break;
}
if(torf ==true){
throw new MyException("图书不存在异常");
}
return in2;
}
//通过序号
public static int input3() throws MyException{
System.out.println("请输入序号:");
Scanner input3 =new Scanner(System.in);
int in3 =input3.nextInt();
if(in3<=0||in3>array.length){
throw new MyException("图书不存在异常");
}else{
System.out.println(array[in3-1].toString());
}
return in3;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean judge = false;
//循环try-catch
do{
try{
switch(input1()){
case 1:
input2();
break;
case 2:
input3();
break;
}
System.out.println("谢谢使用!");
judge =true;
}catch(MyException e){
//e.printStackTrace();
System.out.println(e.getMessage());
System.out.println("请重新输入!");
}
}while(judge ==false);
}
}
打开App,阅读手记