Spencer Salomons
Spencer Salomons

Reputation: 13

Having an issue with retrieving a character

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.

Upvotes: 0

Views: 36

Answers (2)

aaryno
aaryno

Reputation: 636

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.

Upvotes: 2

roeygol
roeygol

Reputation: 5038

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

if (unitString.equals("m")) {..}

Upvotes: 1

Related Questions