callback
callback

Reputation: 4122

Something is wrong in this if else statement?

When I print the content of the message, it always gives me "underweight" although displaybmi is not <19

public String BMImessage(){
    SharedPreferences customSharedPreference = getSharedPreferences(
            "myCustomSharedPrefs", Activity.MODE_PRIVATE);

    String Height = customSharedPreference.getString("heightpref", "");
    String Weight = customSharedPreference.getString("weightpref", "");

    float weight = Float.valueOf(Weight);
    float height = Float.valueOf(Height);

    float displaybmi = weight/(height*height);
    if (displaybmi <19) 
        message = "Underweight" ;
    else if (displaybmi >=19 && displaybmi <=25) 
        message = "Desirable Weight";
    else if (displaybmi >=26 && displaybmi <=29) 
        message =  "Overweight" ;
    else if (displaybmi >=30 && displaybmi <=40) 
        message =  "Obese";
    else if (displaybmi >40) 
        message = "Extremely Obese" ;
    return message;
}

Upvotes: 1

Views: 232

Answers (3)

Paul Vargas
Paul Vargas

Reputation: 42060

If you want to compare two floats, the you can use Float.compare(float f1, float f2)

if (Float.compare(displaybmi, 19) < 0) 
    message = "Underweight" ;
else if (Float.compare(displaybmi, 19) >= 0 && Float.compare(displaybmi, 25) <= 0)
...

The Javadoc says:

Compares two Float objects numerically. There are two ways in which comparisons performed by this method differ from those performed by the Java language numerical comparison operators (<, <=, ==, >=, >) when applied to primitive float values:

  • Float.NaN is considered by this method to be equal to itself and greater than all other float values (including Float.POSITIVE_INFINITY).
  • 0.0f is considered by this method to be greater than -0.0f. This ensures that the natural ordering of Float objects imposed by this method is consistent with equals.

Upvotes: 0

Tim
Tim

Reputation: 1286

Also double check your calculations:

float displaybmi = weight/(height*height);

This works if your weight is in Kilograms and the height is in Meters. If your weight is in pounds and the height in inches you need to add the conversion factor:

float displaybmi = (weight * 703.0)/(height * height);

Calculate-Your-Body-Mass-Index

Upvotes: 1

Chris Thompson
Chris Thompson

Reputation: 35598

What is the value of displaybmi? Try changing the comparison to use 19.0 to ensure that no truncation is happening. You're comparing a float (displaybmi) to an int (19) which can result in undesired behavior.

Upvotes: 3

Related Questions