异常处理练习题所遇到的错误
问题:try catch 在一个包含输入的循环里,catch语句块无限循环执行。
一切源于这道题
数字格式异常
编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户再次输入数字。
输入格式:
i 9 (第1次输入) l 8 (第2次输入) 5 6 (第3次输入)
输出格式:
Incorrect input and re-enter two integers: (第1次输出提示) Incorrect input and re-enter two integers: (第2次输出提示) Sum is 11 (输出结果)
输入样例:
i 9 l 8 5 6
输出样例:
Incorrect input and re-enter two integers: Incorrect input and re-enter two integers: Sum is 11
我的思路是这样的:
- 首先,这个程序应该是应该死循环
while(true){...}
- 输入和输出都写在
try
块里 - 如果两个整数都输入正确则输出结果,
break
跳出循环 catch
块里输出错误提示,然后continue
让程序继续执行
于是有了下面的程序:
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int a,b;
while(true){
try{
a=in.nextInt();
b=in.nextInt();
System.out.println("Sum is "+(a+b));
break;
}catch(java.util.InputMismatchException e){
System.out.println("Incorrect input and re-enter two integers:");
continue;
}
}
}
}
但是程序并没有像预想的一样正常执行,运行结果如下:
catch语句块的内容循环输出,思考了一下,凭借之前C语言编程的经验,应该是输入流中的内容没有被取走,从而导致循环获取,循环抛异常,catch块循环执行。
解决办法:
JAVA中没有C语言中的 fflush()
方法,但是依然很容易解决,在上面的程序中,多加一行 in.nextLine()
就可以达到效果,使程序正常运行。
最终的代码:
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int a,b;
while(true){
try{
a=in.nextInt();
b=in.nextInt();
System.out.println("Sum is "+(a+b));
break;
}catch(java.util.InputMismatchException e){
System.out.println("Incorrect input and re-enter two integers:");
in.nextLine();
continue;
}
}
}
}