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



我要求用户输入2个浮点,并需要验证用户是否正确输入了2个浮点。我使用"Scanner"读取用户的输入,并使用".hasNextFloat(("验证用户的输入是否为浮点。我的代码如下。但我发现,当第一次运行do..while循环时,我编写的代码只会验证用户的第一次输入,所以如果用户的输入是(字符+浮点(,代码可以得出正确的结果。但是,如果用户的输入是(float+字符(,那么它将崩溃,因为它将绕过do..while循环,直接转到firstN=readInput1.nextFloot((;secondN=readInput1.nextFloot((因此,我想知道如何使用do…while循环检查两个输入。非常感谢。

public static void main(String[] args) {
System.out.printf("Welcome to Lucy's Get 2 Floats Program! nn");
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! nn");
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:");
}
}
}

相关内容

  • 没有找到相关文章

最新更新