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

时间:2016-02-17 01:52:04

标签: java validation double

我的问题实际上只涉及我应该在哪里检查以确保输入是整数的代码。感谢任何帮助过的人。

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

2 个答案:

答案 0 :(得分:1)

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

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

如果你想用科学记数法处理双打(例如3.4-e20),请使用:

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

对于整数,您可以在上面的每个正则表达式中使用.之前的部分。像

Pattern.compile("\\d+")

对于可能有签名的数字,

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

注意最后一个末尾的+。必须至少有一个数字才能使其符合数字,因此您无法使用*,这意味着零或更多次出现

正则表达式here的Javadoc。

regexr中测试双重模式。

答案 1 :(得分:0)

您的解决方案应该有效,因为任何整数都会解析为double。您可以将其设置为更详细,并且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;
}