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\$

migrated from stackoverflow.com Jun 11 '16 at 16:00

This question came from our site for professional and enthusiast programmers.

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\$
  • \$\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 Jun 11 '16 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, privacy policy and cookie policy