Home Java Java-tips Examples-introductory Dialog Dialog I/O: Kilometers to Miles

Ask Questions?

View Latest Questions

Advertisement


 
 

Dialog I/O: Kilometers to Miles
Posted on: July 26, 2006 at 12:00 AM
This basic program asks the user for a number of miles and converts it to kilometers.

Java Notes

Dialog I/O: Kilometers to Miles

This basic program asks the user for a number of miles and converts it to kilometers. It uses JOptionPane for all input and 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.

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 
 26 
 27 
 28 
 29 
 30 
 31 
// File   : intro-dialog/KmToMiles.java
// Purpose: Converts kilometers to miles.
// Author : Fred Swartz
// Date   : 24 Aug 2005

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

public class KmToMiles {

    //... Static constants
    static final double MILES_PER_KILOMETER = 0.621;                          //Note 1

    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);                               //Note 2

        //... Computation
        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.
Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com