Java String Conversion Numeric type exception given default value

Source: Internet
Author: User

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 PlainCopy
    1. Numberutils.toint (Userinfo.getuserport (), 0); Conversion failure returns the default value of 0
源码示例:
[Java]View PlainCopy
  1. /**
  2. * @param str The string to convert, could 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 String Conversion Numeric type exception given default value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.