如何检查用户输入的数据类型有效性(Java Scanner 类)

Ton*_*yGW 3 java double

我正在尝试制作一个简单的用户界面,要求用户输入双精度类型数字,如果他们的输入不是双精度类型,程序应继续打印提示,直到用户输入有效的双精度类型。我下面的代码还不能正常工作,因为当用户输入有效的双精度类型时,程序不会执行任何操作,除非用户输入另一个双精度类型数字。我猜想 while 循环中的条件 (sc.hasNextDouble()) 消耗了第一个有效输入。如何纠正这个问题?多谢

Scanner sc = new Scanner(System.in);

System.out.println("Type a double-type number:");
while (!sc.hasNextDouble())
{
    System.out.println("Invalid input\n Type the double-type number:");
    sc.next();
}
userInput = sc.nextDouble();    // need to check the data type?
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 6

由于您可能无法输入双精度值,因此最好读取字符串,然后尝试将其转换为双精度值。标准模式是:

Scanner sc = new Scanner(System.in);
double userInput = 0;
while (true) {
    System.out.println("Type a double-type number:");
    try {
        userInput = Double.parseDouble(sc.next());
        break; // will only get to here if input was a double
    } catch (NumberFormatException ignore) {
        System.out.println("Invalid input");
    }
}
Run Code Online (Sandbox Code Playgroud)

在输入 double 之前循环无法退出,之后userInput将保留该值。

另请注意,通过将提示放入循环内,可以避免无效输入时出现代码重复。