Java Notes

Example: Dialog: Kilometers to Miles

This program asks the user for a number of miles and converts it to kilometers.

Dialog Input / Output

Convert String to a number. We have to convert the input string to a number to 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().

Sample dialog boxes from program

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: Dialog IO for read-compute-write program, named constants.
// Author : Fred Swartz - 2007-01-18 - Placed in public domain.

import javax.swing.*;  // Package containing JOptionPane

public class KmToMiles {
    //==================================================================== constants
    static final double MILES_PER_KILOMETER = 0.621;                       //Note 1

    //========================================================================= main
    public static void main(String[] args) {
        //... Input
        String kmStr = JOptionPane.showInputDialog(null, "Enter number of kilometers.");
        double kilometers = Double.parseDouble(kmStr);                     //Note 2

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

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

Notes

  1. Constant values are commonly declared static final before the methods are defined. The 'static' keyword will be explained later. If a variable is defined with the 'final' attribute, it's value can't be changed after an assignment to it, which is exactly what you want to do to prevent a constant from being changed.
  2. You can only do arithmetic operations on numbers in Java, but showInputDialog returns a string. It's necessary to convert the string to a number. Here we convert the string to a double.