0

I'm trying to make a program that will give you your "ideal" weight, and think I have it mostly figured out. However, when I run the code nothing happens. I think this is because it's not properly retrieving the indicator if it should be metric or imperial.

String name, heightString, unitString; double height;

    name = nameInput.getText();
    unitString = unitInput.getText();
    heightString = heightInput.getText();

    height = Double.parseDouble(heightString);

    if (unitString == "m")
    {
        outputLabel.setText(name + "'s ideal weight is" + (height * height * 25) + "kgs");
    }

    else if (unitString == "i")
    {
        outputLabel.setText(name + "'s ideal weight is" + (height * height * 25 / 703 + "lbs"));
    }

That's what I have, I'm fairly sure the issue is I didn't have the condition for the if statement correct, but I'm not able to find what I should be doing.

Schwern
  • 153,029
  • 25
  • 195
  • 336

2 Answers2

2

Is this Java? If so, then == will not work to compare strings. Use .equals():

name = nameInput.getText();
unitString = unitInput.getText();
heightString = heightInput.getText();

height = Double.parseDouble(heightString);

if ("m".equals(unitString))
{
    outputLabel.setText(name + "'s ideal weight is" + (height * height * 25) + "kgs");
}
else if ("i".equals(unitString))
{
    outputLabel.setText(name + "'s ideal weight is" + (height * height * 25 / 703 + "lbs"));
}

Put your String literal ("m") first to avoid a NullPointerException if unitString is null.

Tom
  • 16,842
  • 17
  • 45
  • 54
aaryno
  • 606
  • 5
  • 13
1

in Java use .equals() instead of == like:

if (unitString.equals("m")) {..}
roeygol
  • 4,908
  • 9
  • 51
  • 88
  • `==` checks for reference equality (ie. are they the same object, not if they have the same content). For more detail, see https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Schwern Jan 18 '15 at 02:02