Search code examples
javaif-statementwhile-loopdo-loops

How to create a conversion of Fahrenheit to Celsius in java


The code should output a table for Fahrenheit and Celsius:

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |", temp);
            double sum = (temp + (9.0/5.0)) * 32;   
            System.out.printf("%5d", (int) sum );
            System.out.println();
        }
}  

Solution

  • How to create a conversion of Fahrenheit to Celsius in java

    The most important step IMHO is to understand the problem before ever thinking about coding.

    Wikipedia is a good start and searching for Celsius it give us:

    [°C] = ([°F] − 32) ×  5⁄9

    In Java that would be something like:

    celsius = (fahrenheit -32.0) * 5.0 / 9.0;
    

    I think it is best to do that in a separate method so it is easier to test it:

    public static double fahrenheitToCelsius(double fahrenheit) {
        double celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
        return celsius;
    }
    

    Note 1: it is worth testing this method before going on - two significant temperatures are:

    • 32°F == 0°C (melting point of ice)
    • 212°F == 100°C (boiling point of water)

    so just do something quick & dirty like:

    System.out.println("32 == " + fahrenheitToCelsius(32));
    System.out.println("212 == " + fahrenheitToCelsius(212));
    

    much better, maybe a bit to heavy in that simple case, is to use some framework like JUnit.

    Note 2: for creating the table do as posted in the question, but only one printf to take advantage of having the format together at one place (obviously after calling above method):

    System.out.printf("%5.0f | %5.1f\n", fahrenheit, celsius);
    

    Note 3: caution with 5/9 - in Java that is interpreted as integer division and would result in zero!

    (above code is just a sample and was not tested or debugged