Home Java Java-tips Examples-introductory Dialog Kilometer to Miles - Formatted

Ask Questions?

View Latest Questions

Advertisement


 
 

Kilometer to Miles - Formatted
Posted on: July 26, 2006 at 12:00 AM
This program is the same as Kilometers to Miles.

Java Notes

Kilometer to Miles - Formatted

This program is the same as Kilometers to Miles, but it formats the output to display the output to only one decimal place. It also shows how to define a constant.

Source code

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
// File   : intro-dialogKmToMiles.java
// Purpose: Converts kilometers to miles.  Formats output.
// Author : Michael Maus
// Date   : 16 Apr 2005

import javax.swing.*;  // Package containing JOptionPane
import java.text.*;    // Package containing DecimalFormat

public class KmToMilesFormatted {

    //... Static constants
    static final double MILES_PER_KILOMETER = 0.621;                          //Note 1
    static final DecimalFormat ONE_DECIMAL_PLACE = new DecimalFormat("0.0");  //Note 2

    public static void main(String[] args) {

        //... Variables
        String kmStr;       // String version of km before conversion to double.
        double kilometers;  // Number of kilometers.
        double miles;       // Number of miles.

        //... Input
        kmStr = JOptionPane.showInputDialog(null, "Enter number of kilometers.");
        kilometers = Double.parseDouble(kmStr);

        //... Computation
        miles = kilometers * MILES_PER_KILOMETER;

        //... Output
        JOptionPane.showMessageDialog(null, kilometers + " kilometers is "
                                    + ONE_DECIMAL_PLACE.format(miles) + " miles.");
    }
}

Notes

Note 1: Constant values are commonly declared static final before the methods are defined.

Note 2: The string pattern that's passed to the DecimalFormat constructor shows how many digits are printed after the decimal point.

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com