我要用户输入2个浮点数,并且需要验证用户是否正确输入了2个浮点数。我正在使用“扫描程序”读取用户输入,并使用“ .hasNextFloat()”来验证用户输入是否为浮点型。我的代码如下。但是我发现我编写的代码仅在第一次运行do..while循环时才验证用户的首次输入,因此,如果用户的输入为(字符+浮点数),则代码可以得出正确的结果。但是,如果用户的输入是(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:");
}
}
}