如何检查用户输入的数据类型有效性(Java Scanner类) [英] how to check the data type validity of user's input (Java Scanner class)

查看:1261
本文介绍了如何检查用户输入的数据类型有效性(Java Scanner类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的用户界面,要求用户输入双重类型的数字,如果他们的输入不是双重类型,程序应该继续打印提示,直到用户输入有效的双重类型。我的下面的代码还没有完成,因为当一个用户键入一个有效的double类型时,除非用户键入另一个double类型的数字,否则程序不会执行任何操作。我猜在while循环中的条件(sc.hasNextDouble())消耗第一个有效的输入。如何纠正?感谢很多

I am trying to make a simple UI that asks users to input double-type numbers, if theirs input is not of double type, the program should keep printing the prompt until user inputs a valid double type. My code below is not quite working yet, because when a user types in a valid double type, the program does not do anything unless the user types another double type number. I guess the condition (sc.hasNextDouble()) in the while loop consumes the first valid input. How to correct this? thanks a lot

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?


推荐答案

由于您可能获得双输入,最好读取一个字符串,然后尝试将其转换为双倍。标准模式是:

Since you may not get a double entered, best to read in a String, then attempt to convert it to a double. The standard pattern is:

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");
    }
}

循环不能退出,直到双已经输入,之后 userInput 将保存该值。

The loop can't exit until a double has been entered, after which userInput will hold that value.

还要注意如何将提示放在循环中,你可以避免无效输入的代码重复。

Note also how by putting the prompt inside the loop, you can avoid code duplication on invalid input.

这篇关于如何检查用户输入的数据类型有效性(Java Scanner类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆