码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-12-06 14:40:23      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:自定义   get   mod   board   字符串   plain   ted   数值类型   pop   

 

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

 

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

标签:自定义   get   mod   board   字符串   plain   ted   数值类型   pop   

原文地址:http://www.cnblogs.com/ydxblog/p/7992181.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!