java判断一个字符串是否为数字型

摘自:https://blog.csdn.net/qq_42133100/article/details/92158507

方法一:用JAVA自带的函数(只能判断正整数 )

2 public static boolean isNumeric(String str){
3    for (int i = str.length();--i>=0;){  
4        if (!Character.isDigit(str.charAt(i))){
5            return false;
6        }
7    }
8    return true;
9 }

  

方法二:正则(推荐,速度最快)

public static boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
}

  

方法三:正则

public static boolean isNumeric(String str){
    Pattern pattern = Pattern.compile("[0-9]*");
    return pattern.matcher(str).matches();   
}

  

方法四:正则

public final static boolean isNumeric(String s) {
    if (s != null && !"".equals(s.trim()))
        return s.matches("^[0-9]*$");
    else
        return false;
}  

  

方法五:用ascii码 

public static boolean isNumeric(String str){
    for(int i=str.length();--i>=0;){
        int chr=str.charAt(i);
        if(chr<48 || chr>57)
            return false;
    }
   return true;
}  

  

方法六:采用强制类转换来判断一个字符串是否为数字 (有局限性,如果要判断是int型或double型,就必须要调整转换语句,但可以判断正负)

try {  
        //Integer num = Integer.valueOf(str);  
        Double num2 = Double.valueOf(str);  
        //System.out.println("Is Number!" + num);  
        System.out.println("Is Number!" + num2);  
} catch (Exception e) {  
        System.out.println("Is not Number!");  
}

  

方法七:采用正则表达式的方式来判断一个字符串是否为数字,这种方式判断面比较全面,可以判断正负、整数小数 (推荐)

//?:0或1个, *:0或多个, +:1或多个 
 Boolean strResult = str.matches("-?[0-9]+.?[0-9]*");     
 if(strResult == true) {  
            System.out.println("Is Number!");  
        } else {  
            System.out.println("Is not Number!");  
        }

  

猜你喜欢

转载自www.cnblogs.com/xinruyi/p/11518617.html