简体   繁体   中英

JAVA if Statement works and doesn't work at the same time

The problem is my if Statement. The second if works as designed, it prints out what I asked, but the first one does not even though they are formatted the same way, and defaults to the else statement. I just want to know what I did wrong.

The First if

     if(systemChoice.equals("M")){
        weight = height * height * 25;
        outputLabel.setText(name + ", your ideal weight is " + weight + " kgs.");

The Second if

    if(systemChoice.equals("I")){
        weight = height * height * 25 / 703;
        outputLabel.setText(name + " , your ideal weight is " + weight + " lbs");
    }

And here is the whole program in context if necessary

     String name, systemChoice;
    double height, weight;

    name = nameInput.getText();
    systemChoice = systemInput.getText();
    height = Double.parseDouble(heightInput.getText());

    /*Calculates your ideal weight 
    *based on a bmi formula in 
    *your preferred system of measurement
    *Imperial or Metric
    */
    if(systemChoice.equals("M")){
        weight = height * height * 25;
        outputLabel.setText(name + ", your ideal weight is " + weight + " kgs.");
    }
    if(systemChoice.equals("I")){
        weight = height * height * 25 / 703;
        outputLabel.setText(name + " , your ideal weight is " + weight + " lbs");
    }
    else{
        outputLabel.setText("Error. Check your System input and try again.");
    }
}          

Your second if (along with it's else branch) is always executed since your first if doesn't have an else branch. To fix this add an else branch to your first if:

if (...) {
   ...
} else if (...) {
   ...
} else {
   ...
}

MRoffel..You should use else if in the second if..

Every time you enter M, the first if actually work, and change the text as you want. But the second if will always fail and prints the else block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM