java 使用 parseDouble 检查 null 的更短方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6284490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shorter way to check for null with parseDouble?
提问by Beetroot
amountStr
is a value that occasionally contains a double value represented as a string.
amountStr
是一个偶尔包含表示为字符串的双精度值的值。
I want to use Double.parseDouble
to read it into a double
variable: amountDbl
.
我想用Double.parseDouble
它读入一个double
变量:amountDbl
.
this.amountDbl = Double.parseDouble(amountStr);
It seems to throw a NullPointerException
if amountStr
doesn't have a value.
它似乎抛出一个NullPointerException
ifamountStr
没有价值。
Does this mean I have to write a check like this every time?
这是否意味着我每次都必须像这样写支票?
if(amountStr!=null)
this.amountDbl = Double.parseDouble(amountStr);
Because I have so many statements like this in my code, I'm hoping for a more concise way of doing this check (or avoiding it).
因为我的代码中有很多这样的语句,所以我希望有一种更简洁的方法来执行此检查(或避免它)。
回答by aioobe
You get a conciser expression if you use the ternary operator:
如果使用三元运算符,则会得到更简洁的表达式:
this.amountDbl = amountStr != null ? Double.parseDouble(amountStr) : 0;
or write your own utility function
或编写自己的效用函数
public static double parseDoubleOrNull(String str) {
return str != null ? Double.parseDouble(str) : 0;
}
and do
并做
this.ammountDbl = parseDoubleOrNull(ammountStr);
Note however that this doesn't protect you against malformed doubles. If this is a concern I suggest you go with the utility function and do something like this:
但是请注意,这并不能保护您免受格式错误的双打。如果这是一个问题,我建议您使用实用程序功能并执行以下操作:
public static double parseDoubleSafely(String str) {
double result = 0;
try {
result = Double.parseDouble(str);
} catch (NullPointerException npe) {
} catch (NumberFormatException nfe) {
}
return result;
}
If you're after concise code you could even do
如果你追求简洁的代码,你甚至可以做
import static pkg.UtilClass.parseDoubleSafely;
回答by oluies
- Create a wrapper class for the amount that handles this test in the constructor/factory or handles a null amount as a special case, eg the Null option pattern
- Use a Java utility library like guava that implements a Optional(expected to come in Guava r10)
Google Guava has a
T firstNonNull(T first,T second)
that can be used asDouble.parseDouble( Objects.firstNonNull(amountStr,"0") )
(Switch to Scala and use the Option Pattern)
- 为在构造函数/工厂中处理此测试的数量创建一个包装类,或者将空数量作为特殊情况处理,例如Null 选项模式
- 使用 Java 实用程序库,如实现Optional 的guava (预计在 Guava r10 中出现)
谷歌番石榴有一个
T firstNonNull(T first,T second)
可以用作Double.parseDouble( Objects.firstNonNull(amountStr,"0") )
(切换到 Scala 并使用 Option Pattern)
回答by user2940338
Might be a couple of years late to answer this question. The NumberUtils Class in org.apache.commons.lang3.math package has a method createDouble that does what you are asking for(https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#createDouble-java.lang.String-)
回答这个问题可能晚了几年。org.apache.commons.lang3.math 包中的 NumberUtils 类有一个方法 createDouble 可以满足您的要求(https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/ lang3/math/NumberUtils.html#createDouble-java.lang.String-)
回答by Smart Coder
I was initializing an object and needed to convert from String to Double and ran in to null values from String.
我正在初始化一个对象,需要从 String 转换为 Double 并从 String 运行到 null 值。
A a = new A(value1, value2 == null ? null : Double.parseDouble(value2), value3....);
A a = new A(value1, value2 == null ? null : Double.parseDouble(value2), value3....);
回答by Evan Mulawski
Why not initialize it beforehand to a "default" value?
为什么不事先将其初始化为“默认”值?
String amountStr = /* some default value */
Then, when you use the variable, check for that special case.
然后,当您使用该变量时,请检查该特殊情况。
if (amountDbl != /* some default value */)
//parse it
回答by Ryan Amos
You could always surround it with try/catch or use a ternary operator (as aioobe did)
你总是可以用 try/catch 包围它或使用三元运算符(就像 aioobe 那样)
try{
this.amountDbl = Double.parseDouble(amountStr);
} catch (Exception ex){
ex.printStackTrace();
}
回答by mamboking
It's not much better but you could do:
这不是更好,但你可以这样做:
this.amountDbl = Double.parseDouble(amountStr==null ? "" : amountString);
回答by Sergio Marquez
I use this:
我用这个:
Double.parseDouble(str.isEmpty()?"0":str);
Double.parseDouble(str.isEmpty()?"0":str);
or
或者
Double.parseDouble((str==null||str.isEmpty())?"0":str);
Double.parseDouble((str==null||str.isEmpty())?"0":str);