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

 public static boolean isNumeric(String str){
    for (int i = str.length();--i>=0;){ 
       if (!Character.isDigit(str.charAt(i))){
            return false;
        }
    }
    return true;
 }

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

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

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐