当前这是我的代码,当用户未选择A,B,C,D,E或F作为选择时,我需要显示“请输入有效的选择”。问题是如果我在“ else”条件上加上“请输入一个有效的...”语句,Java会要求我初始化变量ActivityFactor,因为如果用户未选择正确的选择就不会有变量。有人知道我该如何解决吗?或有任何想法我应该如何编写程序来做到这一点?

if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
            ActivityFactor = 1.0;

        else if ((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("B"))
        ActivityFactor = 1.3;

        else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("C"))
        ActivityFactor = 1.6;
        else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("C"))
        ActivityFactor = 1.5;
        else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("D"))
        ActivityFactor = 1.7;
        else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("D"))
        ActivityFactor = 1.6;
        else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("E"))
        ActivityFactor = 2.1;
        else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("E"))
        ActivityFactor = 1.9;
        else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("F"))
        ActivityFactor = 2.4;
        else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("F"))
        ActivityFactor = 2.2;
        else
        {
       ActivityFactor = -1;

    }

    //After
    if(ActivityFactor != -1){
     tdee = (nBMR * ActivityFactor);
     System.out.println(tdee);}
    else
   { System.out.println("Please enter a valid choice");
    }

最佳答案

在有条件之前将ActivityFactor初始化为通常的值。

例如,您可以这样做:

// knowing that it can never be -1
// so if that value remains, you know that user entered wrong letter
ActivityFactor = -1

// then the conditional begins
if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
...

// after conditional...
if(activityFactor != -1){
    double TDEE = (nBMR * ActivityFactor);
}


顺便说一句,我建议您使用“ activityFactor”而不是ActivityFactor。

10-05 20:07