2016-03-06 74 views
0
do{ 
    try{ 
     System.out.println("Please enter the publication year :"); 
     year=keyboard.nextInt(); 
     doneYear=true; 
    } catch(InputMismatchException e) { 
     System.out.println("Please enter a number."); 
    } 
} while(!doneYear); 

这不起作用。一旦我遇到第一个异常,它会无限循环。要求输入,直到他输入一个数字?

+0

我想你需要'keyboard.next()'你的catch块 –

+0

内作品。谢谢!! –

回答

1

nextXYZ()方法(尤其是nextInt())在使用InputMismatchException失败时不会消耗令牌。如果发生这种情况,您需要使用当前错误的令牌以继续并获得新令牌。否则,你只是不断重新评估,再不成的输入,从而导致无限循环,你观察到:

do { 
    try { 
     System.out.println("Please enter the publication year :"); 
     year = keyboard.nextInt(); 
     doneYear = true; 
    } catch (InputMismatchException ignore) { 
     keyboard.nextLine(); // consume and ignore current input 
     System.out.println("Please enter a number."); 
    } 
} while (!doneYear); 
相关问题