[英]Looping Try Statement
我每次抛出异常时都试图循环一个try块。
例如,当程序提示输入double并且用户输入字符串时,会抛出NumberFormatException。 因此程序将请求用户重新输入。
这就是我目前正在做的事情。 这是正确的方法还是有更好的方法?
// infinite loop
for (;;)
{
try
{
//do something
break; // if an exception is not thrown. it breaks the loop.
}
catch (Exception e)
{
//display the stack trace.
}
// restarts the for loop
}
而不是根据输入抛出异常,通过使用正则表达式来保持对用户输入的限制。 Java正则表达式将在这一点上帮助您。
import java.util.Scanner;
import java.util.regex.Pattern;
public class Sample
{
private final static Pattern DIGITS = Pattern.compile( "\\d*" );
public static void main ( String [] args )
{
Scanner scanner = new Scanner( System.in );
while ( true )
{
String input = scanner.nextLine();
if ( evalInput( input ) )
process( input );
else
System.out.println("Input constraints: it must be just numerical.");
}
}
public static void process ( String str )
{
// Whatever you wanna do with the accepted input.
}
public static boolean evalInput ( String str )
{
if ( str != null && DIGITS.matcher( str ).matches() )
return true;
return false;
}
}
我会像你一样做,也许会添加一个重新进入的提示。
while(true) {
try {
String s = read.nextLine();
i = Integer.parseInt(s);
break;
} catch(NumberFormatException) {
System.out.println("Please try again.");
continue;
}
}
在这种情况下,我宁愿把整个try-block放在循环中。 我认为阅读比打破尝试更容易:
while (true) {
try {
...
} catch (...) {
...
}
}
此外,我更清楚地写入while (true)
无限循环,并且不会正常地使用异常来处理用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.