Jon
Jon

Reputation: 31

Temperature Conversion not working properly in JFrame

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:

Upvotes: 2

Views: 193

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

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

Related Questions