不匹配异常麻烦

时间:2014-02-24 02:52:33

标签: java exception try-catch java.util.scanner mismatch

不知道如何实现不匹配异常。如果它应该是一个int并且没有程序崩溃,我如何键入一个字母?

try { 
  System.out.print("Enter graduation year : ");
  year = response.nextInt();
} catch (InputMismatchException ex) {
  while (year < 1920 || year > 2010) {
  System.out.print("invalid value. Enter a year between 1920 and 2010 : " );
  year = response.nextInt();
}

2 个答案:

答案 0 :(得分:2)

不,您不希望在catch块中获取输入,而是想要警告用户该块中的错误输入。相反,在扫描仪nextInt()之后的try块中设置一个布尔值。在while循环中包围整个事物,并且只有在成功设置boolean时才退出while循环。

伪代码:

initialize boolean variable, inputStillBad to true. 
while inputStillBad
  try block
    prompt user for input
    get input from scanner
    if this line was reached, then scanner succeeded
    check if year is within bounds, and if so:
      set inputStillBad to false.
    else:
      warn user that the year was out of range
  catch your exception here
    warn the user that they entered non-numeric input
end while loop

答案 1 :(得分:1)

您可以检查用户是否输入了Int,如下所示:

if(response.hasNextInt())
{
 year = response.nextInt();
}