如何检查字符串是float还是int?

Ali*_*Ali 1 java string int

我有一个字符串,我知道只包含一个数字.

我想检查这个数字是int还是float.

YCF*_*F_L 16

有很多方法可以解决您的问题,例如您可以使用try{}catch(){}:

解决方案1

public static void main(String[] args) {
    String str = "5588";
    //check if int
    try{
        Integer.parseInt(str);
    }catch(NumberFormatException e){
        //not int
    }
    //check if float
    try{
        Float.parseFloat(str);
    }catch(NumberFormatException e){
        //not float
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案2

或者你可以使用正则表达式[-+]?[0-9]*\.?[0-9]+:

boolean correct = str.matches("[-+]?[0-9]*\\.?[0-9]+");
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看此匹配浮点数与正则表达式