我面对的是java.util.InputMismatchException;
我捕获了InputMismatchException,但我不明白为什么它在接受第一个错误的输入后会进入无限循环,并且输出是这样的:
enter two integers
exception caught这会不断重复
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flag = 0;
while (flag != 1) {
try {
System.out.println("enter two integers");
int a = sc.nextInt();
int b = sc.nextInt();
int result = a + b;
flag = 1;
System.out.println("ans is" + result);
} catch (NumberFormatException e) {
System.out.println("exception caught");
} catch (InputMismatchException e) {
System.out.println("exception caught");
}
}
}发布于 2016-05-18 15:39:41
您需要清除缓冲区,以便在抛出异常后它不会对nextInt()无效。添加一个finally块并在其中调用sc.nextLine():
while (flag != 1) {
try {
System.out.println("enter two integers");
int a = sc.nextInt();
int b = sc.nextInt();
int result = a + b;
flag = 1;
System.out.println("ans is" + result);
} catch (NumberFormatException e) {
System.out.println("exception caught");
} catch (InputMismatchException e) {
System.out.println("exception caught");
} finally { //Add this here
sc.nextLine();
}
}发布于 2016-05-18 15:24:11
如果您按enter键,则还需要使用此字符
int a = sc.nextInt();
int b = sc.nextInt();
sc.nextLine ();然后你就可以进入
2 3 <CR>发布于 2016-05-18 15:29:23
在您的代码中,您捕获了InputMisMatchException,并且您只是打印了一条消息,这将导致再次转到while循环。
int a = sc.nextInt();
int b = sc.nextInt();当这两行中的任何一行抛出异常时,您的flag=1将不会被设置,并且您将处于无限循环中。纠正您的异常处理,或者中断循环,或者通过将扫描仪输入读取为字符串来清除它。
https://stackoverflow.com/questions/37292789
复制相似问题