Java请求双倍

时间:2013-05-15 19:03:16

标签: java computer-science object-oriented-analysis

如果在我的程序中使用scanner.NextDouble()并且用户输入的内容不是双重的,即任何类型的字符,我如何重新提示它们输入有效的双?我尝试抛出异常并捕获它,但我所做的只是告诉他们这是错误的,我不知道如何将控制权转回try块。如果有人有任何意见,将不胜感激!

private double requestDoubleFromUser( String prompt )
{
    /*** Local Variables ***/

    Scanner sc = new Scanner( System.in );
    double userInput = 0;

    try
    {
    /*** Get input from user ***/

    System.out.print( prompt );
    userInput = sc.nextDouble();
    }

    catch( Exception e )
    {
        System.out.println("That was not a double");
    }

    return userInput;
}

感谢

2 个答案:

答案 0 :(得分:3)

您可以使用while循环,如下所示:

double userInput = 0;
boolean done = false;
while (!done) {
    try {
        /*** Get input from user ***/
        System.out.print( prompt );
        userInput = sc.nextDouble();
        done = true;
    } catch( Exception e ) {
        System.out.println("That was not a double");
    }
}

答案 1 :(得分:0)

您可以将呼叫置于循环中Scanner#nextDouble,并通过捕获InputMismatchException来使用非数字类型。使用Double类型允许循环继续检查输入值。

Scanner sc = new Scanner(System.in);
Double userInput = null;

while (userInput == null) {
    try {
        System.out.print("Enter double:");
        userInput = sc.nextDouble();
    } catch (InputMismatchException e) {
        System.out.println("That was not a double: " + sc.nextLine());
    }
}