循环尝试声明

时间:2012-02-03 05:59:45

标签: java exception loops logic try-catch

每次抛出异常时,我都会尝试循环一个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
}

3 个答案:

答案 0 :(得分:3)

不是根据输入抛出异常,而是通过使用正则表达式来限制用户输入。 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;
    }
}

答案 1 :(得分:3)

我会像你一样做,也许会添加一个重新输入的提示。

while(true) {
  try {
    String s = read.nextLine();
    i = Integer.parseInt(s);
    break;
  } catch(NumberFormatException) {
    System.out.println("Please try again.");
    continue;
  }
}

答案 2 :(得分:0)

在这种情况下,我宁愿把整个try-block放在循环中。我认为这比阅读更容易阅读:

while (true) {
    try {
        ...
    } catch (...) {
        ...
    }
}

另外,我更清楚地为无限循环编写while (true),并且不会正常地使用异常来处理用户输入。

相关问题