Java Notes

Example: Kilometers to Miles - Try-Catch

This program asks the user for a number of miles and converts it to kilometers, like other examples. This adds two features to the plain version.

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 
 34 
 35 
 36 
// File   : examples/dialog/KmToMilesTryCatch.java
// Description: Converts kilometers to miles.
// Illustrates: Use of try-catch for NumberFormatException.
//              Loop which exits with a break.
//              Be sure comment on break attracts attention.
// Author : Fred Swartz - 2007-01-19 - Placed in public domain.

import javax.swing.*;

public class KmToMilesTryCatch {
    //==================================================================== constants
    static final double MILES_PER_KILOMETER = 0.621; 
    
    //========================================================================= main
    public static void main(String[] args) {
        while (true) {
            try {                                                           //Note 1
                //... Input
                String kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
                if (kmStr == null || kmStr.equals("")) {
                    break;   // Exit from loop.  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                }
                double kilometers = Double.parseDouble(kmStr);              //Note 2
                
                //... Computation
                double miles = kilometers * MILES_PER_KILOMETER;
                
                //... Output
                JOptionPane.showMessageDialog(null, kilometers + " kilometers is "
                                                  + miles + " miles.");
            } catch (NumberFormatException nfe) {                           //Note 3
                JOptionPane.showMessageDialog(null, "Input must be a number.");
            }
        }
    }
}

Notes

  1. The code in the try clause executes normally. If an exception is thrown in the try clause, execution continues immediately in the catch clause.
  2. parseDouble can throw a NumberFormatException.
  3. This only catches NumberFormatExceptions.