有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java这个if-else语句中有什么错误吗?

当我打印邮件内容时,尽管displaybmi不是<;十九,

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;
}

共 (3) 个答案

  1. # 1 楼答案

    还要仔细检查你的计算:

    float displaybmi = weight/(height*height);
    

    如果你的体重以千克为单位,身高以米为单位,这个方法就有效。如果您的体重以磅为单位,身高以英寸为单位,则需要添加换算系数:

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

    Calculate-Your-Body-Mass-Index

  2. # 2 楼答案

    体重指数的值是多少?尝试将比较更改为使用19.0,以确保没有发生截断。您正在将float(displaybmi)与int(19)进行比较,这可能会导致不良行为

  3. # 3 楼答案

    如果要比较两个浮点数,可以使用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)
    ...
    

    报告说:

    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.