Java- 如何让验证器检查输入是否为双精度数和整数

Java- how to get the validator to check if input is a double and a whole number

我的问题真的只是关于我应该把检查以确保输入是整数的代码位放在哪里。感谢所有帮助过的人。

public static String getQuantity(String aQuantity){
    while (isValidQuantity(aQuantity)== false ){
        errorMessage += "Enter Valid quantity\n";
    }
    return aQuantity;
    }
    private static boolean isValidQuantity(String aQuantity){
    boolean result = false;
    try{
        Double.parseDouble(aQuantity);
     //here?//
        result = true;
    }catch(Exception ex){
        result = false;
    }

    return result;
}

您可以使用正则表达式轻松完成。双重使用:

Pattern.compile("\d+\.\d+")

如果您想处理科学记数法中的双精度数(例如 3.4-e20),请使用:

Pattern.compile("[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?")

对于整数,您可以简单地使用上面每个正则表达式中 . 之前的部分。喜欢

Pattern.compile("\d+")

对于可能有符号的数字,

Pattern.compile("[-+]?[0-9]+")

注意最后一个结尾的+。必须至少有一位数字才能作为数字,因此您不能使用 *,这意味着 零次或多次出现 .

正则表达式的 Javadocs here

测试 regexr 中替身的模式。

您的解决方案应该可行,因为任何整数也将解析为双精度数。你可以让它更冗长,让 0 代表无效 1 代表一个 int 和 2 代表一个双精度。

private static int isValidQuantity(String aQuantity){
    int result = 0;
    //first try int
    try{
        Integer.parseInt(aQuantity);
        result = 1; //the parse worked
    }catch(NumberFormatException ex){
        result = 0;
    }

    if(result == 0)
    {
        //if it's not an int then try double
        try{
            Double.parseDouble(aQuantity);

            result = 2; //the parse worked
        }catch(NumberFormatException ex){
            result = 0;
        }
    }

    return result;
}