开发者

how to null a variable of type float

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 oikonom开发者_运维知识库ia = 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() == " "){


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.


You should probably be doing something like this

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

You're going to get a NumberFormatException if you try to parse a string that doesn't translate into a valid number. So you could simply wrap this statement in a try catch block and handle the error properly.

Hope that helps.


try this:

Float oikonomia = null;
try{
  oikonomia = Float.valueOf(vprosvasis7.getText().toString());
}catch(numberFormatException e){
  // logging goes here
}

Now the value is NULL in case of an illegal (non float) string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜