我想用这段代码完成的就是检查用户'输入是整数的输入,然后如果它不是正确的数据类型,则给它们三次输入它的机会。然后,如果他们到达" 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;
答案 0 :(得分:2)
发生这种情况的原因是因为您的扫描仪缓冲区未被清除。输入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并从中捕获异常。