在 Java 中,如何检查浮点变量是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18492432/
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
In Java, how do you check if a float variable is null?
提问by Christopher Treanor
It seems that when it comes to *value.getFloat("Value_Quotient", quotient_Float)==null*, it encounters a problem. How do I fix this?
好像说到*value.getFloat("Value_Quotient", quotient_Float)==null*,就遇到了问题。我该如何解决?
private void Store() {
quotient_Float = posture_error/time;
if(value.getFloat("Value_Quotient", quotient_Float)==null || quotient_Float < value.getFloat("Value_Quotient", quotient_Float))
{
editor.putFloat("Value_Quotient", quotient_Float);
editor.commit();
}
}
采纳答案by Juned Ahsan
float
is a primitive
data type and not an object
. null check is used for objects. For primitives you should use the default values check. For float the default value is 0.0f.
float
是一种primitive
数据类型而不是object
. 空检查用于对象。对于基元,您应该使用默认值检查。对于浮点数,默认值为 0.0f。
回答by Jason Crosby
There is also a Floatclass that you can use. The Float
object can be checked for null
as its an object representation of a float
data type. A Float
object is represented by a capitol F, and the float
data type has a small f. Java preforms autoboxing, which means that you can easily switch back and fourth between the two, i.e:
还有一个浮动类,您可以使用。所述Float
对象可以检查null
作为其的对象表示float
的数据类型。一个Float
对象用大写字母 F 表示,float
数据类型有一个小的 f。Java 预制自动装箱,这意味着您可以轻松地在两者之间来回切换,即:
float number = 0.56f;
Float object = number;
Or the other way around:
或者反过来:
Float object = new Float(1.43);
float number = object;
You can also pass a Float
object into a method where a float
data type is expected, or the other way around.
您还可以将Float
对象传递到需要float
数据类型的方法中,或者反过来。
If checking for the default value doesnt work for whatever reason, this will allow you to check a Float
for null.
如果出于某种原因检查默认值不起作用,这将允许您检查Float
空值。
if (object != null) {
// do what you want to do
}
回答by Dmitry Avgustis
Some points that might be useful(Java 8).
一些可能有用的要点(Java 8)。
Float object can be assigned to a float primitive. Then float primitive can be 0 checked like this:
浮点对象可以分配给浮点基元。然后可以像这样检查浮点基元 0:
Float floatObj = new Float(0);
float floatPrim = floatObj;
if (floatPrim == 0) {
System.out.println("floatPrim is 0"); // will display message
}
However if your Float object is null, than assigning it to a primitive will cause NPE
但是,如果您的 Float 对象为空,那么将其分配给原语会导致 NPE
Float floatObj = null;
float floatPrim = floatObj; //NPE
So be careful here
所以在这里要小心
One more thing, apparently you can use == operator on Float object, since autounboxing happens.
还有一件事,显然你可以在 Float 对象上使用 == 运算符,因为自动拆箱发生了。
Float floatObj = new Float(0.0f);
if (floatObj == 0) {
System.out.println("floatObj is 0"); // will work
}