Java Notes

Java Example: Console: Kilometers to Miles

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

  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 
// File   : examples/console/KmToMilesConsole.java
// Description: Converts kilometers to miles.
// Illustrates: Console IO for read-compute-write program, named constants.
// Author : Fred Swartz - 2007-01-18 - Placed in public domain.

import java.util.*;  // Package containing Scanner

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

    //========================================================================= main
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);                               //Note 2

        //... Input
        System.out.print("Enter number of kilometers: ");
        double kilometers = in.nextDouble();

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

        //... Output
        System.out.println(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. Creates a new Scanner object called "in". Use this to read all values.