java字符串转换数值类型出现异常赋予默认值

http://blog.csdn.net/w47_csdn/article/details/77855126

可以自定义工具方法,例如:

public static int parseInt(String s, int defaultValue) {
 if (s == null) return defaultValue;
 try {
   return Integer.parseInt(s);
  } catch (NumberFormatException x) {
   return defaultValue;
  } 
}
其他的parseLong、parseDouble与之类似。

也可以使用org.apache.commons.lang3.math.NumberUtils提供的工具类,需要导入commons-lang3.jar包

使用示例:
[java] view plain copy
 
  1. NumberUtils.toInt(userInfo.getUserPort(), 0);// 转换失败返回默认值0  
源码示例:
[java] view plain copy
 
  1. /**   
  2.   * @param str  the string to convert, may be null 
  3.   * @param defaultValue  the default value 
  4.   * @return the int represented by the string, or the default if conversion fails 
  5.   * @since 2.1 
  6.   */  
  7.  public static int toInt(String str, int defaultValue) {  
  8.      if(str == null) {  
  9.          return defaultValue;  
  10.      }  
  11.      try {  
  12.          return Integer.parseInt(str);  
  13.      } catch (NumberFormatException nfe) {  
  14.          return defaultValue;  
  15.      }  
  16.  }  
原文地址:https://www.cnblogs.com/ydxblog/p/7992181.html