2016-12-04 84 views
-1

我试图用Integer.parseInt()String转换为int,如果不工作,catchNumberFormatException该程序返回并重新提示用户。的Integer.parseInt()崩溃Java程序

但是,当我输入非String的值时,程序会冻结,而不是重新渲染我。

这里是我的代码片段:

keepLooping = true; 
    while(keepLooping) { 
     String unconvertedString = ""; 
     int convertedInt = 0; 
     try { 
     System.out.print("Enter a string to be parsed into an integer: "); 
     unconvertedString = userInput.next(); 
     convertedInt = Integer.parseInt(unconvertedString); 
     keepLooping = false; 
     } 
     catch (NumberFormatException e) { 
     userInput.next(); 
     } 
    } 
+0

因此,它提供了一个int时正常工作? userInput究竟是什么? – Reisclef

+0

你认为'next()'做了什么? –

+0

'userInput'是什么?和'userInput.next()'做了什么? – YoungSpice

回答

0

您需要的catch子句中摆脱userInput.next()的。

catch (NumberFormatException e) { 
    //userInput.next(); 
} 

只要让它继续循环,如果发生异常。