O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required