已解决java.lang.NumberFormatException异常的正确解决方法,亲测有效!!!已解决java.lang.NumberFormatException异常的正确解决方法,亲测有效!

编程知识 更新时间:2023-05-01 22:59:16

已解决java.lang.NumberFormatException异常的正确解决方法,亲测有效!!!

文章目录

    • 报错问题
    • 解决方法
    • 福利

报错问题

粉丝群里面的一个小伙伴敲代码时发生了报错(当时他心里瞬间凉了一大截,跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug不会解决的小伙伴),报错信息如下:


在调用StringUtils.split()和Integer.parseInt()时经常遇见这样的问题,不管传入的参数的值是什么,都能进入不为null或”“的判断中,然后就运行执行下面的代码,就可能出现 java.lang.NumberFormatException: For input string: "null"的异常,提示出现问题的位置在“Integer id = Integer.parseInt(idStr);”这是因为如果传入给Integer.parseInt()的值为空或者StringUtils.split()对空字符串进行切割无意义。如果传入的值不为null或“”可以正常运行不报错,如果为空值就会出现任如下异常。

by: java.lang.NumberFormatException:<u> </u>For input string: "null"  
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)  
    at java.lang.Integer.parseInt(Integer.java:580)  
    at java.lang.Integer.parseInt(Integer.java:615) 

这里的For input string: “null”
并不是指传入的值为空,而是指传入的字符串为“null”,而“null”并不能被 StringUtils.split()切割,进而不能被Integer.parseInt()调用,所以会报错。

if(customerIdStr != null && !customerIdStr.equals("") ){  
            String[] customerIds = customerIdStr.split(",");  
            //将字符串客户ID 转换为整数ID  
            for (String idStr : customerIds) {  
              Integer id = Integer.parseInt(idStr);  
                customerRepository.updatefixedAreaId(fixedAreaId,id);  
            }  
        }else{  
                return;  
        }  

解决方法

解决方法如下


所以只需要在上面的判断语句后面再加一个判断传入的参数是否不为“null”的条件即可解决此类异常问题。

if(customerIdStr != null && !customerIdStr.equals("") && !customerIdStr.equals("null")){  
            String[] customerIds = customerIdStr.split(",");  

福利

每周会送6本技术书籍包邮到家
由于博主时间精力有限,每天私信人数太多,没办法每个粉丝都及时回复
大家可以进社区裙或者添加博主微信
点击下方链接即可
http://t.csdn/6kInJ

更多推荐

已解决java.lang.NumberFormatException异常的正确解决方法,亲测有效!!!已解决java.lang.NumberFormatExce

本文发布于:2023-04-24 10:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/1bf9637f1a48fda03bf99a70ee6b048d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解决方法   异常   正确   java   lang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 100262文章数
  • 26023阅读数
  • 0评论数