java中判断字符串是否为数字的方法的几种方法

来源:互联网 发布:安妮宝贝老公 知乎 编辑:程序博客网 时间:2024/05/23 05:08
 
  1. ava中判断字符串是否为数字的方法: 
  2.  
  3. 1.用JAVA自带的函数 
  4. public staticboolean isNumeric(String str){ 
  5.   for (int i =0; i < str.length(); i++){ 
  6.    System.out.println(str.charAt(i)); 
  7.    if (!Character.isDigit(str.charAt(i))){ 
  8.     return false
  9.    } 
  10.   } 
  11.   return true
  12.  
  13. 2.用正则表达式 
  14. 首先要import java.util.regex.Pattern 和 java.util.regex.Matcher 
  15. public boolean isNumeric(String str){  
  16.    Pattern pattern = Pattern.compile("[0-9]*");  
  17.    Matcher isNum = pattern.matcher(str); 
  18.    if( !isNum.matches() ){ 
  19.        return false;  
  20.    }  
  21.    return true;  
  22.  
  23. 3.使用org.apache.commons.lang 
  24. org.apache.commons.lang.StringUtils; 
  25. boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789"); 
  26. http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释: 
  27. isNumeric 
  28. public staticboolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returnsfalse
  29. null will returnfalse. An empty String ("") willreturn true
  30. StringUtils.isNumeric(null)   = false 
  31. StringUtils.isNumeric("")     =true 
  32. StringUtils.isNumeric("  ")   = false 
  33. StringUtils.isNumeric("123")  =true 
  34. StringUtils.isNumeric("12 3") = false 
  35. StringUtils.isNumeric("ab2c") =false 
  36. StringUtils.isNumeric("12-3") = false 
  37. StringUtils.isNumeric("12.3") =false 
  38.   
  39. Parameters: 
  40. str - the String to check, may be null  
  41. Returns: 
  42. true if only contains digits, and is non-null 
  43.   
  44. 上面三种方式中,第二种方式比较灵活。 
  45.   
  46. 第一、三种方式只能校验不含负号“-”的数字,即输入一个负数-199,输出结果将是false; 
  47.   
  48. 而第二方式则可以通过修改正则表达式实现校验负数,将正则表达式修改为“^-?[0-9]+”即可,修改为“-?[0-9]+.?[0-9]+”即可匹配所有数字。