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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM