Search code examples
javaswingjoptionpane

Celsius is always 0.0?


I'm making a simple temperature conversion program in Java that converts Fahrenheit to Celsius. My program compiles just fine, but no matter what number I input, it always says that Celsius is 0.0! What could I be doing wrong? Here is my full code:

import javax.swing.JOptionPane;

public class FahrenheitToCelsius {

public static void main(String[] args) {

    double fahrenheit, celsius;

    String input = JOptionPane.showInputDialog("Please enter the temperature in Fahrenheit:");

    fahrenheit = Double.parseDouble(input.trim());

    celsius = (5 / 9) * (fahrenheit - 32);

    JOptionPane.showMessageDialog(null, "The temperature is " + celsius + " degrees celsius.");

    }

}

Solution

  • It's because (5 / 9) = 0.

    5 and 9 are both ints, and int division here will result in 0 (5/9 = 0.555..., which can't be an int so it is truncated to 0). Use doubles (5.0 / 9.0) and you won't have this problem.