Program: TempConverter

The program shown in Example 5-5 prints a table of Fahrenheit temperatures (still used in daily life weather reporting in the United States) and the corresponding Celsius temperatures (used in science everywhere, and in daily life in most of the world).

Example 5-5. TempConverter.java

import java.text.*;

/* Print a table of fahrenheit and celsius temperatures 
 */
public class TempConverter {

    public static void main(String[] args) {
        TempConverter t = new TempConverter(  );
        t.start(  );
        t.data(  );
        t.end(  );
    }

    protected void start(  ) {
    }

    protected void data(  ) {
        for (int i=-40; i<=120; i+=10) {
            float c = (i-32)*(5f/9);
            print(i, c);
        }
    }

    protected void print(float f, float c) {
        System.out.println(f + " " + c);
    }

    protected void end(  ) {
    }
}

This works, but these numbers print with about 15 digits of (useless) decimal fractions! The second version of this program subclasses the first and uses a DecimalFormat to control the formatting of the converted temperatures (Example 5-6).

Example 5-6. TempConverter2.java

import java.text.*; /* Print a table of fahrenheit and celsius temperatures, a bit more neatly. */ public class TempConverter2 extends TempConverter { protected DecimalFormat df; public static void main(String[] args) { TempConverter t = new TempConverter2( ); t.start( ); t.data( ); t.end( ); } // Constructor public TempConverter2( ) { df = new DecimalFormat("##.###"); } protected void print(float f, float c) { System.out.println(f + " " + df.format(c)); ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.