一直在无限循环中,终于解决了。。
package trycatch.JieShuXiTong;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Created by Administrator on 2017/3/28.
*/
public class JieShuXiTong {
String[] name = {"科幻世界", "空之境界", "发条女孩", "三体", "深渊上的火", "安德的游戏", "天渊", "狼人十字架", "时砂之王"};
String[] xuHao = {"1-", "2-", "3-", "4-", "5-", "6-", "7-", "8-", "9-",};
public static void main(String[] args) {
System.out.println("您好,欢迎您的到来,目前图书馆可供借阅的图书有:");
JieShuXiTong js = new JieShuXiTong();
//循环遍历输出序号和书名
for (int i = 0; i < js.name.length; i++) {
System.out.print(js.xuHao[i]);
System.out.print(js.name[i]);
if (i < js.name.length - 1) System.out.print(";");
}
System.out.println("");
System.out.println("请选择您查找图书的方式");
//定义一个boolean类型的变量,初始值为true
boolean bl=true;
//while循环,这样当不想让他循环时给赋值成false就好了
//给整个循环体加了try块。异常只有两种可能一种是数组遍历时越界,还有一种是类型不匹配,比如int类型你输入胡汉字
//或者字符就不对了
while (bl) {
try {
System.out.println("输入1,按书名查找图书");
System.out.println("输入2,按图书序号查找图书");
Scanner a = new Scanner(System.in);
int num = a.nextInt();
if (num == 1) {
System.out.println("请输入您要查询的书的名字");
String name2 = a.next();
for (int i = 0; i < js.name.length; i++) {
if (name2.equals(js.name[i])) {
System.out.println("book:" + name2);
bl=false;
break;
} else if (i == js.name.length - 1) {
System.out.println("图书不存在或输入异常,请重新输入");
}
}
}else if (num == 2) {
System.out.println("请输入您要查询的书的号码");
int num2 = a.nextInt();
System.out.println("book:" + js.name[(num2 - 1)]);
bl=false;
}else{
System.out.println("您的输入有误请重新操作");
continue;
}
} catch (InputMismatchException e) {
System.out.println("您的输入格式有误,请重新输入");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("您的输入的号码已超过当前最大书号,请重新输入");
}
}
}
}