# Java: Kilometer to Miles - Formatted

      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
     34
     35
     36
     37
    // KmToMiles.java --  Converts kilometers to miles.
    // Michael Maus, 9 Sept 2004
    //
    // Note: Formats the miles to one decimal place.

    import javax.swing.*;
    import java.text.*;

    public class KmToMilesFormatted {

        public static void main(String[] args) {
            //... Constants
            final double MILES_PER_KILOMETER = 0.621;
            final DecimalFormat ONE_DECIMAL_PLACE = new DecimalFormat("0.0");

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

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

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

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

            //... Stop
            System.exit(0);  // Stop GUI program
        }
    }