gpt4 book ai didi

Java如何验证2个输入是否为 float

转载 作者:行者123 更新时间:2023-12-01 16:59:06 25 4
gpt4 key购买 nike

我要求用户输入 2 个 float ,并且需要验证用户是否正确输入了 2 个 float 。我使用“扫描仪”来读取用户的输入,并使用“.hasNextFloat()”来验证用户的输入是否为 float 。我的代码如下。但我发现我编写的代码只会在第一次运行 do..while 循环时验证用户的第一个输入,因此如果用户的输入是(字符+ float ),则代码可以得出正确的结果。但是如果用户的输入是(float + character),那么它就会崩溃,因为它会绕过do..while循环,直接进入firstN = readInput1.nextFloat();secondN = readInput1.nextFloat() ; 因此,我想知道如何使用 do...while 循环检查两个输入。谢谢!

public static void main(String[] args) {

System.out.printf("Welcome to Lucy's Get 2 Floats Program! \n\n");

Scanner readInput1 = new Scanner(System.in);

float firstN;
float secondN;

do
{
System.out.println("Please enter two floats separated by a space: ");
while(!readInput1.hasNextFloat()) {
System.out.println("You have entered an invalid choice. Please try again:");
readInput1.next();
readInput1.next();
}
} while(!readInput1.hasNextFloat());

firstN = readInput1.nextFloat();
secondN = readInput1.nextFloat();
System.out.printf("You have entered two valid floats: %5.2f and %5.2f", firstN, secondN);

}

最佳答案

这段代码有效,但我不知道它是否是最好/最有效的方法:

public static void main(String[] args) {

System.out.printf("Welcome to Lucy's Get 2 Floats Program! \n\n");

Scanner readInput1 = new Scanner(System.in);

float firstN;
float secondN;

System.out.println("Please enter two floats separated by a space: ");
boolean loop = true;
while(loop) {
if (readInput1.hasNextFloat()) {
firstN = readInput1.nextFloat();
if (readInput1.hasNextFloat()) {
secondN = readInput1.nextFloat();
System.out.printf("You have entered two valid floats: %5.2f and %5.2f", firstN, secondN);
loop = false;
} else {
System.out.println("You have entered an invalid choice. Please try again:");
readInput1.next();
}
} else {
readInput1.next();
readInput1.next();
System.out.println("You have entered an invalid choice. Please try again:");
}
}

}

关于Java如何验证2个输入是否为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61541066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com