zoukankan      html  css  js  c++  java
  • 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.  }  
  • 相关阅读:
    Java_zip_多源文件压缩到指定目录下
    Linux:ps -ef命令
    Linux:find命令中
    String.split()与StringUtils.split()的区别
    StringUtils工具类的常用方法
    Java:substring()
    Java:indexof()
    Linux:grep命令
    12、spring工厂+web前台搭建
    11、redis使用ruby实现集群高可用
  • 原文地址:https://www.cnblogs.com/ydxblog/p/7992181.html
Copyright © 2011-2022 走看看