java determines whether a string of numeric

Excerpt: https: //blog.csdn.net/qq_42133100/article/details/92158507

 

Method a: built-in function of the JAVA (only determines a positive integer)

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 }

  

Method two: regular (recommended, fastest)

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

  

Method three: Regular

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

  

Method four: Regular

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

  

Method five: ascii code with 

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

  

Six: the forced class switching to determine whether a string of numbers (with limitations, is to judge if the int type or double type, it is necessary to adjust the conversion statement, but can be positive or negative judgment)

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!");  
}

  

Method 7: The regular expression way to determine whether a string to a number, this way judge fairly comprehensive, based on positive and negative, decimal integer (recommended)

// ?: 0 or 1, *: 0 or more, +: 1 or more  
 Boolean strResult = str.matches ( "- [0-9] + [0-9] *?.?");      
 IF (== strResult to true) {   
            System.out.println ( "Is Number The!");   
        } the else {   
            System.out.println ( "Number The Is Not!");   
        }

  

Guess you like

Origin www.cnblogs.com/xinruyi/p/11518617.html