Java – how to make a variable of type float null

If my float variable is set to 0, my code works, but if my variable is null, I want my code to work How can I do that? This is a snippet of code I wrote:

float oikonomia= (float)((float)new Float(vprosvasis7.getText().toString()));

                         if(oikonomia==0){

I tied if (oikonomia = = null) or if (oikonomia = null) but it didn't work

P. S.: another way is to initially set oikonomia = 0; Also, if the user changes it, go to my if session It doesn't work 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){

It doesn't work either:

Float oikonomia = Float.valueOf(vprosvasis7.getText().toString());

                         if(oikonomia.toString() == " "){

Solution

If you want a floating-point number that can be null, try float instead of float

Float oikonomia= new Float(vprosvasis7.getText().toString());

But it will never be empty like your example

Editor: Aaaah, I'm beginning to understand your problem You really don't know what vprosvas7 contains and whether it is properly initialized to numbers So try this and:

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 many ways to simplify the above and write clearer code But I think this should explain how to correctly and safely parse a string into a float without encountering any exceptions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>