0
\$\begingroup\$

I am creating this converter. There are three units that can be converted: kelvin, celcius and fahrenheit. I used two variables to check which unit is chosen. It's cek and cek2. Is there any way I can shorten this code, or I just have to add all possible combination using if statements as i am doing now?

 if (cek=="celcius"&&cek2=="celcius"){
  hasil.setText(nilai.getText());
  } //celcius ke celcius

  if (cek=="celcius"&&cek2=="fahrenheit"){
  double hasil1 = (nilai1*9/5)+32;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }

  if (cek=="celcius"&&cek2=="kelvin"){
  double hasil1 = nilai1+273.15;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }

  if (cek=="fahrenheit"&&cek2=="celcius"){
  double hasil1 = (nilai1-32)*5/9;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }
  ....................................
\$\endgroup\$
0

2 Answers 2

0
\$\begingroup\$

You can shorten that code by not converting the values directly, but rather use common intermediate representation. E.g. you could convert the incoming number first to celsius (not matter what source and destinations are) and then convert the intermediate representation to the target:

double inputTemperature = ... ;
double outputTemperature;
String inputUnit = ... ;
String outputUnit = ... ;
// input conversion if necessary
if (inputUnit.equals("fahrenheit")) {
    inputTemperature = fahrenheitToCelsius(inputTemperature);
}
if (inputUnit.equals("kelvin")) {
    inputTemperature = kelvinToCelsius(inputTemperature);
}
// output conversion:
if (outputUnit.equals("fahrenheit")) {
    inputTemperature = celsiusToFahrenheit(inputTemperature);
}
if (outputUnit.equals("kelvin")) {
    inputTemperature = celsiusToKelven(inputTemperature);
}

So only 4 if statements rather than 9.

P.S.: Please review https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

\$\endgroup\$
1
  • \$\begingroup\$ You declare outputTemperature variable but never use it... It would be more readable if you use three varables: inputTemperature, intermediateTemperature and outputTemperature, and use them all in appropriate order. \$\endgroup\$
    – CiaPan
    Commented Jun 11, 2016 at 16:20
0
\$\begingroup\$

You should make your variable names easier to understand. Also, you should probably use enums.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.