Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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)); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata