0

I'm a beginner with java and I can't seem to figure out why string won't convert to boolean.

The error code comes up specifically on the "if" line and "else if" line.

    String Name, SystemOfMeasure;
    Double Height, IdealWeight;

    // Retrieve user data
    Name = txtName.getText();
    SystemOfMeasure = txtSystemOfMeasure.getText();
    Height = Double.parseDouble(txtHeight.getText());

    if (SystemOfMeasure = "M") {
        IdealWeight = Height * Height * 25;
        lblDisplay.setText(Name + ("'s ideal weight is") + IdealWeight);
    } else if (SystemOfMeasure = "I") {
        IdealWeight = Height * Height * 25 / 703;
        lblDisplay.setText(Name + ("'s ideal weight is") + IdealWeight);
    } else {
        lblDisplay.setText("Please enter M or I");
    }
developer
  • 20,716
  • 8
  • 46
  • 63

2 Answers2

5

You are currently assigning the value M to SystemOfMeasure, but if or else if conditions expect a boolean expression, NOT an assignment.

So, you need to use .equals() method (which returns true/false) for string comparisons like SystemOfMeasure.equals("M") as shown below:

if (SystemOfMeasure.equals("M")) {
     //add your code
} else if (SystemOfMeasure.equals("I") {
    //add your code
} else {
    //add your code
}

Also, remember that, you need to follow the java naming standards like lower case for variable names like systemOfMeasure

developer
  • 20,716
  • 8
  • 46
  • 63
0

The code has syntax error. The if-condition needs to be a boolean or an expression that evaluates to a boolean.

= is the assignment operator in Java, whereas == is the conditionality or relational operator. So you should use == instead of =.

Having said that, String equality is a bit more complex Read StackOverflow answer here and so you should use String.equals() to compare two strings. So correct code would be:

if (SystemOfMeasure.equals("M")) {
    IdealWeight = Height * Height * 25;
    lblDisplay.setText(Name + ("'s ideal weight is") + IdealWeight);
}

but if SystemOfMeasure was say an int, you could have used

if(SystemOfMeasure == 1) { 
 //do this
}
Community
  • 1
  • 1