避免 parseInt 为输入字符串抛出 NumberFormatException 的正确方法:“”
当我运行 parseInt: 时
Integer.parseInt(myString);
,它会抛出:
NumberFormatException: For input string: ""
这是否意味着我已经做了类似的事情?
if(StringUtils.isNotBlank(myString))
return Integer.parseInt(myString);
else
return 0;
When I run parseInt:
Integer.parseInt(myString);
it throws:
NumberFormatException: For input string: ""
Does this mean I have do something like this?
if(StringUtils.isNotBlank(myString))
return Integer.parseInt(myString);
else
return 0;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,但是:将其包装在一个简单的方法中(并消除多余的
else
),或者使用现有的实现,例如公共资源Lang 的NumberUtils.toInt(str, defaultValue)
:此方法处理
null
值和转换失败。自己编写相同的内容非常简单:
NumberFormatExtension
异常Yes, but: Wrap it in a thin method (and eliminate the redundant
else
), or use an existing implementation, like Commons Lang'sNumberUtils.toInt(str, defaultValue)
:This method handles
null
values and conversion failures.Writing the same thing on your own is straight-forward:
NumberFormatExtension
exception那么,您可以改用条件运算符:
如果您需要在多个位置执行此操作,您可能希望将其放入单独的方法中。请注意,您还应该考虑
myString
为 null 或包含非数字文本的情况。Well, you could use the conditional operator instead:
If you need to do this in multiple places, you'd probably want to put this into a separate method. Note that you should also consider situations where
myString
is null, or contains non-numeric text.如果字符串可以为空,我会这样做:
当我不确定它只包含数字时:
If the string can be empty I do it this way:
When I'm not sure it contains only digits:
你所拥有的很好,但作为一种编码风格,我更喜欢使测试“积极”(
isBlank
),而不是“消极”(isNotBlank
),即或者,更多简洁地说:
What you have is fine, but as a coding style I prefer to make tests "positive" (
isBlank
), rather than "negative" (isNotBlank
), ieor, more succinctly:
是的。 (在对输入内容做出假设之前先验证您的输入。:-)
+1 表示已经找到 Apache 的 common-lang w/ StringUtils 。
Yes. (Validate your inputs before making assumptions about what are in them. :-)
+1 for already finding Apache's common-lang w/
StringUtils
.Integer.parseInt(String)
不接受非数字输入,包括 null 和空字符串。要么像你建议的那样防范这种情况,要么抓住 NFE。
Integer.parseInt(String)
doesn't accept non-numeric input, including nulls and empty strings.Either guard against that like you suggested, or catch the NFE.
我不知道为什么我要寻找这个,但这是一个简单的方法:
I don't know why was I searching for this but here's the easy way: