问题描述:关闭第一个Scanner输入流,第二个Scanner输入流异常
无异常代码
public static void test() {
boolean f1 = true;
boolean f2 = true;
boolean f3 = true;
int up = 0, down = 0, high = 0;
double area = 0.0;
System.out.println("-------");
System.out.println("求梯形面积");
System.out.println("-------");
while (f1) {// 保证输入数据正确
try {
System.out.println("梯形上低:");
Scanner in = new Scanner(System.in);
up = in.nextInt();
if (up <= 0) {// 几何图形边长大于0
System.out.println("数据值异常!");
continue;
}
} catch (InputMismatchException e) {
System.out.println("数据类型异常");
continue;
}
f1 = false;
}
while (f2) {
try {
System.out.println("梯形下低:");
Scanner in = new Scanner(System.in);
down = in.nextInt();
if (down <= 0) {
System.out.println("数据异常!");
continue;
}
} catch (InputMismatchException e) {
System.out.println("数据类型异常");
continue;
}
f2 = false;
}
while (f3) {
try {
System.out.println("梯形高:");
Scanner in = new Scanner(System.in);
high = in.nextInt();
if (high <= 0) {
System.out.println("数据异常!");
continue;
}
} catch (InputMismatchException e) {
System.out.println("数据类型异常");
continue;
}
f3 = false;
}
area = (up + down) * high / 2.0;//梯形面积
System.out.println("梯形面积:" + area);
}
...
}
...
添加in.close()后,代码出现异常
异常代码片段
public static void test() {
...
while (f1) {// 保证输入数据正确
try {
...
Scanner in = new Scanner(System.in);
...
in.close();//添加这句话后,下面读取输入流出现异常
} catch (InputMismatchException e) {
...
}
...
}
while (f2) {
try {
...
Scanner in = new Scanner(System.in);
down = in.nextInt();//抛出异常:NoSuchElementException
...
} catch (InputMismatchException e) {
...
}
...
}
问题出在哪里?
一般关闭应该放在finally关闭,
try{
}catch(..){
}finally{
in.close;
}
因为你在while的时候f1上已经关闭了呀。后面再调用nextInt就报会错了