-1

如果在我的程序中我使用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;
}

谢谢

4

2 回答 2

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");
    }
}
于 2013-05-15T19:05:29.357 回答
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());
    }
}
于 2013-05-15T19:11:23.450 回答