使用InputMismatchException尝试/ catch创建无限循环 [英] try/catch with InputMismatchException creates infinite loop
问题描述
所以我正在构建一个从用户输入中获取内容的程序。我有一个非常简单的try / catch块,如果用户没有输入int,应该重复该块,直到它们为止。以下是代码的相关部分:
So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Except {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean bError = true;
int n1 = 0, n2 = 0, nQuotient = 0;
do {
try {
System.out.println("Enter first num: ");
n1 = input.nextInt();
System.out.println("Enter second num: ");
n2 = input.nextInt();
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d",n1,n2, nQuotient);
}
}
如果我为第二个整数输入0,那么try / catch完全符合它的预期,并让我再次使用它。但是,如果我有一个InputMismatchException,比如为其中一个数字输入5.5,它只是在无限循环中显示我的错误信息。为什么会发生这种情况,我该怎么办呢? (顺便说一句,我已经尝试显式输入InputMismatchException作为catch的参数,但它没有解决问题。
If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.
推荐答案
当你收到错误时,你需要调用 next();
。另外建议使用 hasNextInt()
You need to call next();
when you get the error. Also it is advisable to use hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}
阅读之前你需要确保扫描仪有一个整数值。你不需要那样的异常处理。
Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.
Scanner scanner = new Scanner(System.in);
int n1 = 0, n2 = 0;
boolean bError = true;
while (bError) {
if (scanner.hasNextInt())
n1 = scanner.nextInt();
else {
scanner.next();
continue;
}
if (scanner.hasNextInt())
n2 = scanner.nextInt();
else {
scanner.next();
continue;
}
bError = false;
}
System.out.println(n1);
System.out.println(n2);
当扫描仪抛出一个InputMismatchException,扫描程序不会传递导致异常的标记,因此可以通过其他方法检索或跳过它。
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
这篇关于使用InputMismatchException尝试/ catch创建无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!