My code is working if my float variable is set to 0, but I want my code to work if my variable is null. How could I do that? Here is a code snippet I wrote:
float oikonomia= (float)((float)new Float(vprosvasis7.getText().toString()));
if(oikonomia==0){
I have tied if(oikonomia==null)
or if(oikonomia=null)
but it is not working.
P.S.: Another way would be to initially set oikonomia=0;
and, if the users change it, go to my if session. This is not working either.
Float oikonomia = Float.valueOf(vprosvasis7.getText().toString());
if(oikonomia.toString() == " "){
float oikonomia= (float)((float)new Float(vprosvasis7.getText().toString()));
oikonomia=0;
if(oikonomia==0){
that way is not working too:
Float oikonomia = Float.valueOf(vprosvasis7.getText().toString());
if(oikonomia.toString() == " "){
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
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. If checking for the default value doesnt work for whatever reason, this will allow you to check a Float for null.
In order to define a null variable, you can use the None keyword. Note: The None keyword refers to a variable or object that is empty or has no value. It is Python's way of defining null values.
"Double" (with an uppercase 'D') is an object that wraps a primitive value. As an object, it can be assigned a null reference. But "double" (with a lowercase 'd') is a primitive type, so it cannot be assigned a null reference.
If you want a nullable float, then try Float
instead of float
Float oikonomia= new Float(vprosvasis7.getText().toString());
But it will never be null
that way as in your example...
EDIT: Aaaah, I'm starting to understand what your problem is. You really don't know what vprosvasis7
contains, and whether it is correctly initialised as a number. So try this, then:
Float oikonomia = null;
try {
oikonomia = new Float(vprosvasis7.getText().toString());
}
catch (Exception ignore) {
// We're ignoring potential exceptions for the example.
// Cleaner solutions would treat NumberFormatException
// and NullPointerExceptions here
}
// This happens when we had an exception before
if (oikonomia == null) {
// [...]
}
// This happens when the above float was correctly parsed
else {
// [...]
}
Of course there are lots of ways to simplify the above and write cleaner code. But I think this should about explain how you should correctly and safely parse a String
into a float
without running into any Exceptions...
Floats and floats are not the same thing. The "float" type in Java is a primitive type that cannot be null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With