Java Notes

Java Example: Kilometers to Miles - Format

This program asks the user for a number of miles and converts it to kilometers, like other examples. However, this version also formats the numbers so that they always have two decimal places to the right of the decimal point.

Dialog Input / Output

Convert String to a number. We have to convert the input string into a number so that we can do the arithmetic with it. This conversion is done by calling Double.parseDouble. If we had wanted an integer instead of a double, we would have called Integer.parseInt.

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 
// File   : examples/dialog/KmToMiles.java
// Description: Converts kilometers to miles.
// Illustrates: Formatting doubles using String.format().
// Author : Fred Swartz - 2007-01-18 - Placed in public domain.

import javax.swing.*; 

public class KmToMilesFormat {
    //==================================================================== constants
    static final double MILES_PER_KILOMETER = 0.621;
    
    //========================================================================= main
    public static void main(String[] args) {
        //... Input
        String kmStr = JOptionPane.showInputDialog(null, "Enter number of kilometers.");
        double kilometers = Double.parseDouble(kmStr);
        
        //... Computation
        double miles = kilometers * MILES_PER_KILOMETER;
        
        //... Output
        String outStr = String.format("%.2f kilometers is %.2f miles.", kilometers, miles);
        JOptionPane.showMessageDialog(null, outStr);
    }
}