我正在做一个项目,并制作了一个read方法来读取用户的输入,但是,如果他们没有输入正确类型的值,我想返回一个print语句,并不断重复这个过程,直到他们输入正确为止。这是到目前为止的代码,但它似乎没有打印我的打印语句。
package Project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Read
{
// Will return user input with exception handling.
public static String read(String label)
{
boolean success = false;
System.out.println( "\nProvide your " + label + ":" );
System.out.print( "> " );
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String value = null;
while (!success) {
try {
value = input.readLine();
success = true;
} catch (IOException ex) {
System.out.println("Sorry that was an invalid input. Try again.");
ex.printStackTrace();
}
}
return value;
}//Read Method.
}//Class.
1条答案
按热度按时间gmol16391#
你需要循环,只要
value
是无效的,所以对你来说value == null || value.isEmpty()
. 所以请提示(>
)也在循环中。我会把错误处理从循环中去掉,因为这不是您可以恢复的东西。这与使用输入无关,但更多的是系统故障,即程序无法读取输入流。所以只要说发生了一个错误就结束了。