我试图用这段代码完成的任务是检查用户的输入是否为整数,然后如果数据类型不正确,则给他们 3 次再次输入的机会。如果达到“maxTries”标记,最后抛出异常。
任何帮助将不胜感激。干杯。
boolean correctInput = false;
int returnedInt = 0;
int count = 0;
int maxTries = 3;
Scanner kybd = new Scanner(System.in);
while(!correctInput)
{
try
{
System.out.println("\nInput your int, you have had:" + count + " tries");
returnedInt = kybd.nextInt();
correctInput = true;
}
catch(InputMismatchException e)
{
System.out.println("That is not an integer, please try again..");
if (++count == maxTries) throw e;
}
}
return returnedInt;
最佳答案
发生这种情况的原因是您的扫描仪缓冲区未清除。输入 kybd.nextInt() 已填充非 int,但由于读取失败,因此实际上并未将其从堆栈中删除。因此,第二个循环它尝试再次拉出已填充的缓冲区,这已经是错误的了。
要解决此问题,您可以在异常处理中使用 nextLine()
清除缓冲区。
} catch (InputMismatchException e) {
System.out
.println("That is not an integer, please try again..");
kybd.nextLine(); //clear the buffer, you can System.out.println this to see that the stuff you typed is still there
if (++count == maxTries)
throw e;
}
另一种选择是使用 String s = kybd.nextLine() 并解析 Integer 并从中捕获异常。
关于Java try catch问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26471387/