0

I'm writing a quick little conversion app for degree conversions and I'm stuck. I'm having issues updating the values by using methods of a different class. Here is my code:

public class AppInfo {
    private double value;
    public double getValue() {
        return value;
    }
    public void setValue(double value) {
        this.value = value;
    }
    public void ConvertF() {
        value = (value * 1.8) + 32;
    }
    public void ConvertC() {
        value = ((value - 32) * (5 / 9));
    }
    public void show() {
        System.out.println(value);
    }
}

My second class (main) is this:

public class Working {
    public static void main(String[] args) {
        System.out.println("Enter degree");
        Scanner sc = new Scanner(System.in);
        double value = sc.nextDouble();
        AppInfo newValue = new AppInfo();
        String answer;
        System.out.println("What unit conversion? C to convert to celsius and F for fahrenheit");
        answer = sc.next();
        newValue.setValue(value);
        if(answer.toLowerCase() == "c") {
            newValue.ConvertC();
        }
        else if(answer.toLowerCase() == "f") {
            newValue.ConvertF();
        }
        newValue.show();
    }
}

Every time I run it, it just returns the same value the user entered in the beginning. It won't update the new value after using the ConvertF/C methods.

I don't know why this is marked as a duplicate. My question isn't about comparing strings so how the hell is it even remotely a duplicate? I just want someone to help me understand what is wrong with my code so I can have a functional program that converts degrees. Simply shutting my question down is demotivating and very irritating. All I want is to know how to fix it/what is wrong.

  • 5
    _Trouble with my first program_ is not a very useful title. Please always write your titles to reflect the actual issue. – Savior Apr 06 '16 at 18:31

1 Answers1

1

You are comparing wrongly the strings, when you do this:

answer.toLowerCase() == "c"

then you are comparing the references and not the content

do instead:

 if(answer.equalsIgnoreCase("c")) {
            newValue.ConvertC();
        }
        else if(answer.equalsIgnoreCase("f")) {
            newValue.ConvertF();
        }

AND this method is not correct:

public void ConvertC() {
        value = ((value - 32) * (5 / 9));
    }

this will set value to 0.0 because you are dividing 5/9 as integer so that result will be an integer (zero)

do this:

public void ConvertC() {
        value = ((value - 32) * (5.0 / 9));
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97