0

好的,所以我使用了许多验证脚本java.util.Scanner,但找不到任何可以帮助我满足我需要的东西。我已经很好地了解了如何设置我的程序,但我仍然需要一些帮助才能让它按照我想要的方式工作。基本上,我的目标是要求用户输入一个高度,并且我想确保它不超过 84 英寸、数字和正数。

到目前为止,这是我的代码:

// the part inside main() that is relevant
double height = 0;
Scanner input = new Scanner(System.in);

height = get_height(height, input);

private static double get_height(double height, Scanner input) {
        do {
            System.out.print("Please enter your height (in inches): ");
            while (!input.hasNextDouble() || input.nextDouble() > 84) {
                if (!input.hasNextDouble()) {
                    System.out.print("You must enter a valid number: ");
                    input.next();
                }
                else if (input.nextDouble() > 84) {
                    System.out.print("Are you really taller than 7 feet? Try again: ");
                    input.next();
                }
            }
            height = input.nextDouble();
        } while (height <= 0);

        return height;
    }

这些是我得到的结果:

Please enter your height (in inches): hey
You must enter a valid number: 100
100
Are you really taller than 7 feet? Try again: 64
(blank space)
64
64

如您所见,或者您可能无法判断,它并没有完全击中应有的正确消息,然后它只留下空白行,您可以在需要之前输入两次数据(如您所见最后两行)。我不知道它为什么这样做,但显然它与我的逻辑有关。我想在循环之后使用 if 语句来验证它是 7 英尺,但如果它无效,那么我该如何重新启动循环?我唯一的想法是创建一个名为“valid”的布尔变量,并最初将其设置为 false,当它为 true 时退出循环并返回。我可以使用一些建议!

哦,对于那些想知道的人来说,这是家庭作业。我并不完全希望我的程序是为我编写的,但是一个建议会很可爱。

编辑:好的,我自己搞定了。感谢我收到的大量帮助..

    private static double get_height(double height, Scanner input) {
    boolean valid = false;
    while (!valid) {
        do {
            System.out.print("Please enter your height (in inches): ");
            while (!input.hasNextDouble()) {
                System.out.print("You must enter a valid number! Try again: ");
                input.next();
            }
            height = input.nextDouble();
            if (height > 84) {
                System.out.println("Are you really over 7 feet? I don't think so..");
                valid = false;
            }
             else {
                valid = true;
            }
        } while (height <= 0);
    }

    return height;
}
4

1 回答 1

0

你能只使用 1 个 do while 循环吗

do {
    //print messages
    height = input.nextDouble();
} while (!"validation conditions");

或者如果你想要不同的消息

boolean valid = false;
do {
    //edit
    System.out.print("Please enter your height (in inches): ");
    while (!input.hasNextDouble()) {
        System.out.print("You must enter a valid number! Try again: ");
        input.next();
    }// end edit

    height = input.nextDouble();
    if(height > 84) {
        valid = false;
        System.out.println("too tall");
    } //add more else if conditions
    else {
        valid = true;
    }
} while (!valid);
于 2013-03-07T02:56:10.087 回答