parseInt()使Java程序崩溃
我正在尝试使用parseInt()使Java程序崩溃,java,exception-handling,numberformatexception,Java,Exception Handling,Numberformatexception,我正在尝试使用Integer.parseInt()将字符串转换为int,如果这不起作用,捕获程序返回的NumberFormatException,并重新编译用户 但是,当我输入一个非字符串值时,程序将冻结,而不是重新编译 以下是我的代码片段: keepLooping = true; while(keepLooping) { String unconvertedString = ""; int convertedInt = 0; try {
Integer.parseInt()
将字符串
转换为int
,如果这不起作用,捕获程序返回的NumberFormatException
,并重新编译用户
但是,当我输入一个非字符串
值时,程序将冻结,而不是重新编译
以下是我的代码片段:
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();
}
}
您需要去掉catch子句中的userInput.next()
catch (NumberFormatException e) {
//userInput.next();
}
如果发生异常,就让它继续循环。这样,当您提供int时,它就可以正常工作了?用户输入到底是什么?你认为next()
做什么?什么是userInput
?而userInput.next()
做什么呢?可能重复的