【问题标题】:Input validation checking if the input is a double输入验证检查输入是否为双精度
【发布时间】:2019-07-09 20:15:24
【问题描述】:

我想检查我输入的数据类型是否正确。例如,如果用户在我希望他们输入double 时输入int,那么程序会告诉他们有错误。这是我目前所拥有的:

System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
try
{
    Double temperature = Double.parseDouble(temp);
}
catch(Exception e)
{
    isValid = false;
    System.out.println("Temperature  must be a double ");
}

当我输入int 时,它所做的只是继续通过程序而不是打印出错误消息。一直坚持这个问题,所以任何帮助都将不胜感激。

【问题讨论】:

  • 每个int 都是有效的double,那么您为什么会期望它失败呢?
  • int 也是double!您也必须针对 intness 进行显式测试。
  • @Harrison Matthews:任何答案对你有用吗?如果是,请考虑接受/支持他们。 What should I do when someone answers my question?

标签: java validation input try-catch


【解决方案1】:

由于您不希望int 被接受,您只需添加一个if 来检查输入String 是否有小数点。

    System.out.println("Enter the temperature in double:");
    String temp = (new Scanner(System.in)).next();
    if (temp.contains(".")) {
        try {
            Double temperature = Double.parseDouble(temp);
        } catch(Exception e) {
            isValid = false;
            System.out.println("Temperature  must be a double ");
        }
    } else {
        isValid = false;
        System.out.println("Temperature  must be a double ");
    }

【讨论】:

  • 只保留原始的 try catch 应该可以解决这个问题,已编辑!
【解决方案2】:

我认为您只想验证十进制数字(不包括整数)。如果是这种情况,那么您可以使用 regex 进行相同的操作:

System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
while (temp != null && !temp.matches("^[0-9]*\\.([0-9]+)+$")) {       // use of regex here
    System.out.println("Enter the temperature in double:");
    temp = input.nextLine();                                          // read input again
}

这将循环直到用户只输入一个有效的十进制输入。 thisregex的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多