简体   繁体   English

Java请求双

[英]Java Requesting Double

If in my program im using scanner.NextDouble() and the user enters something that is not a double ie a char of any kind, how can i re-promt them to enter a valid double? 如果在我的程序中,我使用Scanner.NextDouble()并且用户输入的内容不是双精度数,即任何字符,我如何重新提示它们输入有效的双精度数? I tried throwing an exception and catching it but all i am abel to do is tell them it was wrong, im not sure how to transfer control back to the try block. 我试图抛出一个异常并捕获它,但我唯一想做的就是告诉他们这是错误的,我不确定如何将控制权转移回try块。 if anyone has any input it would be much appreciated! 如果有人有任何意见,将不胜感激!

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;
}

thanks 谢谢

You could use a while loop, something like this: 您可以使用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");
    }
}

You could place the call to Scanner#nextDouble in a loop and consume non numeric types by catching a InputMismatchException . 您可以将对Scanner#nextDouble的调用循环放置,并通过捕获InputMismatchException使用非数字类型。 Using the Double type allows the loop to keep checking for an input value. 使用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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM