所以我正在构建一个从用户输入中获取整数的程序。我有一个似乎非常简单的尝试/捕获块,如果用户不输入 int,则应重复该块,直到他们输入为止。以下是代码的相关部分:
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 会完全按照它应该做的事情,让我再次输入它。但是,如果我有一个 输入错配异常,比如为其中一个数字输入 5.5,它只会在无限循环中显示我的错误消息。为什么会这样,我能做些什么呢?(顺便说一下,我尝试显式键入 InputMismatchException 作为要捕获的参数,但它没有解决问题。
收到错误时需要调用next();
。此外,建议使用hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}
在读取整数值之前,您需要确保扫描仪有一个。而且您将不需要这样的异常处理。
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);
Javadoc of Scanner
当扫描程序引发 InputMismatchException 时,扫描程序将不会传递导致异常的令牌,因此可以通过其他方法检索或跳过该令牌。
> 你也可以尝试以下
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
要遵循debobroto das的答案,你也可以把
input.reset();
input.next();
我遇到了同样的问题,当我尝试这个时。它完全修复了它。
另一个选项是定义 Scanner input = new Scanner(System.in);在 try 块中,每次需要重新输入值时,这将创建一个新对象。
由于try block
中从未到达bError = false
语句,并且语句被击中到所获取的输入,因此它会在无限循环中不断打印错误。
尝试使用 hasNextInt()
以这种方式使用它
catch (Exception e) {
System.out.println("Error!");
input.hasNextInt();
}
或者尝试使用nextLine()
与Integer.parseInt()
结合使用来获取输入。
Scanner scan = new Scanner(System.in);
int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());
补充AmitD的答案:
只需复制/粘贴您的程序并具有以下输出:
Error!
Enter first num:
.... infinite times ....
如您所见,说明:
n1 = input.nextInt();
输入双精度数时会不断抛出异常,这是因为您的流未清除。 要修复它,请按照 AmitD 答案进行操作。
@Limp,你的答案是对的,只需在读取输入时使用.nextLine()。示例代码:
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.nextLine());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.nextLine());
nQuotient = n1 / n2;
bError = false;
} catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d", n1, n2, nQuotient);
请阅读以下链接中有关导致此问题的原因的说明。在此线程中查找我发布的有关详细信息的答案。Java 家庭作业用户输入问题
好的,我将简要描述一下。当您使用 nextInt() 读取输入时,您只是读取数字部分,但 ENDLINE 字符仍在流中。这是主要原因。现在看看上面的代码,我所做的只是阅读整行并解析它,它仍然抛出异常并按照您期望的方式工作。其余代码工作正常。