jeudi 17 décembre 2020

JAVA: If/Else statement not using Else [duplicate]

I am creating a program where a user find's their ideal body weight. They provide their name, height and desired unit (Metric or Imperial).

My problem is that if the 'if' is false (the desired unit is not Metric), it will not complete the 'else' (complete the formula in Imperial units)

Here is my code: Where did I go wrong?

        DecimalFormat x = new DecimalFormat("###,###0.00");
        
        //Define Variables
        String name;
        name = nameInput.getText(); //Get name
        
        double height;
        height = Double.parseDouble (heightInput.getText()); //Get height
        
        String unitinput;
        unitinput = (unitInput.getText()); //Get unit
        
        int unit;
        
        double weight;
        
        //define weight varibale
        double lbs;
        double kg;
        
        //Define height variables
        double inches;
        inches = 1;
        
        double metres;
        metres = inches * 0.0254;
                
        int metric = 0;
        int imperial = 0; 
        
    
        //Find wether user wants metric or imperial
        if (unitinput == "M")
        {
            unit = metric;
        }
        else 
        {
            unit = imperial;
        }

        //Calculate Ideal Weight
        if (unit == metric)
        {
            kg = (height) * (height) * 25;
            outputField.setText(name + "'s ideal weight is: " + x.format(kg) + " kg");
        }
        else
        {
            lbs = (height) * (height) * 25 / 703;
            outputField.setText(name + "'s ideal weight is: " + x.format(lbs) + " lbs");
        }

Aucun commentaire:

Enregistrer un commentaire