mardi 31 mai 2016

How to shorten this if code java

Iam creating this converter. there's 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 iam 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);
  }
  ....................................

Aucun commentaire:

Enregistrer un commentaire