Reputation: 31
I can not seem to figure out what I am doing wrong in my Event Handler; and I am not a good programmer. I can convert from Celsius to Fahrenheit but not the other way around. It usually shows 0.0 for Fahrenheit to Celsius conversions. I think it might have something to do with cfList which is my JComboBox to choose Celsius or Fahrenheit.
Also I want to be able to click the convert button without putting in a value, and the JTextField will automatically be set to zero and show a message that says "Value set to zero."
So how can I get this whole thing to work:
Convert Fahrenheit to Celsius without a value(set to zero)
class TCalcButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
double far, cel;
String ff, cc;
String inString;
inString = tempField.getText();
if(inString==null && cfList.getSelectedIndex() == 0)
{
degree.setText("F");
cel=0;
far = cel*(9/5)+32;
ff = far+"";
resultField.setText(ff);
tempSysField.setText("Value set to zero");
}
if(inString==null && cfList.getSelectedIndex() == 1)
{
degree.setText("C");
far=0;
cel = (5/9)*(far-32);
cc = cel+"";
resultField.setText(cc);
tempSysField.setText("Value set to zero");
}
if(cfList.getSelectedIndex()==0 && inString!=null)
{
degree.setText("F");
cel = Double.parseDouble(inString);
far = cel*(9/5)+32;
ff = far+"";
resultField.setText(ff);
tempSysField.setText("");
}
if(cfList.getSelectedIndex()==1 && inString!=null)
{
degree.setText("C");
far = Double.parseDouble(inString);
cel = (far-32)*(5/9);
cc = cel+"";
resultField.setText(cc);
tempSysField.setText("");
}
}
}
Upvotes: 2
Views: 193
Reputation: 285405
Your question title states:
Temperature Conversion not working properly ...
Almost always this is due to your doing int division unknowingly, and in fact, that's exactly what is going on:
far = cel*(9/5)+32;
Change 9/5 to 9.0/5.0
far = cel * (9.0 / 5.0) + 32;
Why is this important? int division (dividing one int by another) always returns an int, with the fractional part truncated away. So 9/5 returns 1 and 5/9 returns 0. If you want the calculation to retain the fractional portion, then at least one double has to be part of the division equation, so in fact 9.0 / 5 would work just fine as would ((double)9/5)
Upvotes: 4