package Exception;
import java.util.*;
public class bookmanager {
static Books[] book={new Books(1,"数据结构"),new Books(2,"论语")};//静态数组
public static void main(String[] args) {
bookmanager bkm = new bookmanager();
bkm.mainsystem();//调用mainsystem
}
public void mainsystem(){
try{
book();
}catch(BookException e){
System.out.println(e.getMessage());
mainsystem();//如果输入异常,在此调用mainsystem
}
}
public void book() throws BookException{
Scanner in = new Scanner(System.in);
System.out.println("Input Command:1-Base oon name for book;2-Base on number for Book");
try{
int num=in.nextInt();
while(num>book.length || num<=0){//如果num大于数组长度或者小于等于0,重新输入
System.out.println("Inexistence Value! Please Redo!");
num=in.nextInt();
}
booktype(num);
}catch(InputMismatchException e){
throw new BookException("Command Error!");//异常捕获
}
}
public void booktype(int num){
Scanner in = new Scanner(System.in);//输入选项类型
switch(num){
case 1:
System.out.println("The name of the book");
String txt=in.next();
bookselect(txt,0);
break;
case 2:
System.out.println("The number of the book");
num=in.nextInt();
bookselect("",num);
break;
}
}
public void bookselect(String txt,int num){
for(int i=0;i<=book.length;i++){
if(txt.equals(book[i].getName()) || num==book[i].getNum()){
System.out.println("book:"+book[i].getName());//找到,输出名字
return;//找到,返回
}
}
System.out.println("Inexistance Book!");
mainsystem();//for循环之后没找到,调用mainsystem 回到开始
> 上面for循环是见解某位幕友的代码,在此感谢!
}
}
package Exception;
//数组
public class Books {
int num;
String name;
public Books(int num,String name){
this.num=num;
this.name=name;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setNum(int num){
this.num=num;
}
public int getNum(){
return num;
}
}
package Exception;
//自定义异常
@SuppressWarnings("serial")
public class BookException extends Exception{
public BookException(String message){
super(message);
}
}
打开App,阅读手记
热门评论
学习啦!判断的那一段可以修改一下,就可以完全闭环啦。 去掉num=in.nextInt(); 抛出错误的时候,在mainSystem里面就会执行catch里面的语句重新初始化程序啦。