2017-04-22 34 views
0

我试图做一个try-catch语句,当用户输入一个小于0的数字时捕获,然后捕获如果用户输入一个字符/字符串考虑我想要一个int用户。Try-Catch for user input

try { 
    System.out.print("How many square feet are on your lot? (Enter 0 to quit): "); 
    userSquareFeet = scnr.nextInt(); 

    if (userSquareFeet < 0) { 
     throw new Exception("You can't have a negative value"); 
    } 
} catch (InputMismatchException e) { 
    System.out.println("You can not enter a character(s)."); 
} catch (Exception e) { 
    System.out.println(e.getMessage()); 
} 

当我输入一个字符/字符串,它只是启动出于某种原因一个无限循环。任何帮助表示赞赏,对于简单的问题抱歉,Zybooks.com在我看来并没有在这一部分做得很好。

+0

[基本程序挂在nextInt()]的可能重复(http://stackoverflow.com/questions/32151190/basic-program-hanging-at-nextint) – didiz

回答

0

当您使用nextInt()方法时,程序实际上会进入一个循环,直到输入实际上是一个整数。 你的程序输入本身已经是类型限制。