Java 双输入验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23106724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:44:19  来源:igfitidea点击:

Java double Input Validation

java

提问by user3540710

below is the code:

下面是代码:

    Scanner scan = new Scanner(System.in);
    String input = scan.next();
    try{
        double isNum = Double.parseDouble(input);
        if(isNum == Math.floor(isNum)) {
            System.out.println("Input is Integer");
             //enter a double again
        }else {
            System.out.println("Input is Double");
            //break
        }
    } catch(Exception e) {
        if(input.toCharArray().length == 1) {
            System.out.println("Input is Character");
             //enter a double again
        }else {
            System.out.println("Input is String");
            //enter a double again
        }
    }

taken from here: how to check the data type validity of user's input (Java Scanner class)

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

however, when i input 1.0 or 0.0, it is still considered as an integer, is 1.0 not considered a double?

但是,当我输入 1.0 或 0.0 时,它仍然被视为整数,1.0 不视为双精度数吗?

Please help guys, thank you!

请各位大侠帮忙,谢谢!

采纳答案by Ivaylo Slavov

If you want to treat 1.0as a Doublean 1as an Integer, you need to work with the inputvariable, which is of type String.

如果你要正确对待1.0作为Double一个1作为Integer,你需要与工作input变量,它的类型的String

Java will always treat Double x = 1in the same way as Double y = 1.0(meaning 1is a valid Double), so you will not be able to distinguish them with code.

Java 将始终Double x = 1以与Double y = 1.0(意思1是有效的Double)相同的方式处理,因此您将无法通过代码区分它们。

Since you have the original string representation of the input, use a regex or some other validation to check it. For instance a sample regex pattern for double would look like "[0-9]+(\.){0,1}[0-9]*"and for an integer "[0-9]+"or "\d+"

由于您拥有输入的原始字符串表示形式,因此请使用正则表达式或其他一些验证来检查它。例如,double 的示例正则表达式模式看起来像"[0-9]+(\.){0,1}[0-9]*"一个整数"[0-9]+""\d+"

Here is an example:

下面是一个例子:

final static String DOUBLE_PATTERN = "[0-9]+(\.){0,1}[0-9]*";
final static String INTEGER_PATTERN = "\d+";

Scanner scan = new Scanner(System.in);
String input = scan.next();

if (Pattern.matches(INTEGER_PATTERN, input)) {
    System.out.println("Input is Integer");
    //enter a double again
} else if (Pattern.matches(DOUBLE_PATTERN, input)) {
    System.out.println("Input is Double");
    //break
} else {
    System.out.println("Input is not a number");
    if (input.length == 1) {
        System.out.println("Input is a Character");
        //enter a double again
    } else {
        System.out.println("Input is a String");
        //enter a double again
    }
}

回答by Denis Kulagin

Check, if the string you are validating contains a dot - then, if parseDouble succeeds, it could be treated as a double value (even for 1.0).

检查,如果您正在验证的字符串包含一个点 - 那么,如果 parseDouble 成功,它可以被视为双精度值(即使是 1.0)。

回答by Pphoenix

You check if 1.0 is equal to 1, which mathematically is correct. Therefore your first if will return true, and it will be considered an int. It seems that the whole idea with the program is to check doubles and see if they have decimals or not.

您检查 1.0 是否等于 1,这在数学上是正确的。因此,您的第一个 if 将返回 true,它将被视为 int。该程序的整个想法似乎是检查双打并查看它们是否有小数。

回答by Ivaylo Strandjev

1.0is typically considered a valid double, but the code has been written explicitly to threat whole numbers as invalid doubles(printing that they are intergers). To change this behavior remove the inner if:

1.0通常被认为是有效的双精度数,但代码已明确写入威胁整数为无效双精度数(打印它们是整数)。要更改此行为,请在以下情况下移除内部:

try{
    double isNum = Double.parseDouble(input);
    System.out.println("Input is Double");
} catch(Exception e) {
    if(input.toCharArray().length == 1) {
        System.out.println("Input is Character");
    }else {
        System.out.println("Input is String");
    }
}

回答by QBrute

Math.floor(x)

returns a double, and since 1.0 is indeed the same as 1.0, your program will enter the first if-block.

返回一个双精度值,由于 1.0 确实与 1.0 相同,您的程序将进入第一个 if 块。

回答by Raffaele

I think your test is flawed. You say "0.0and 1.0are parsed as integers"based on the condition

我认为你的测试有缺陷。您根据条件说0.0并被1.0解析为整数”

isNum == Math.floor(isNum)

Double-precision floating-point numbers are not a random garbage of bits: they express a precise quantity, and it happens that the numbers zeroand onecan be represented exactly (see the bit patterns)and thus they are equal to Math.floor(val)(btw, this happens for lots of integer values, not only zero and one)

双精度浮点数不是位的随机垃圾:它们表示一个精确的数量,并且恰好可以精确表示数字01 (请参阅位模式),因此它们等于Math.floor(val)(顺便说一句,这发生许多整数值,而不仅仅是零和一)

So you should reconsider your test beforeyour code. Consider that likely a user will never input an integeror a double: what she types is a decimal number, and you should deal with the input depending on what it's used for (the choice is among String, BigDecimal, Number, Integer, Double and so on...)

因此,您应该编写代码之前重新考虑您的测试。考虑到用户可能永远不会输入整数精度数:她输入的是十进制数,您应该根据输入的用途来处理输入(可以选择字符串、BigDecimal、Number、Integer、Double 和很快...)