## Tuesday, April 2, 2013

### Measurement Converter program

The MeasurementConvert program is able to convert from an input number in inch to foot, and centimeter measurements. In this program, you will learn to use the nextFloat() method of Scanner class to get user input, to do some calculations with floating-point numbers, and to format the output by using the format(Format, Text) method.

MeasurementConvert source code:

1. import java.util.Scanner;
2.  class MeasurementConverter
{

3.    public static void main(String[] args)
{

4.       float inch, foot, cent;
5.       Scanner sc=new Scanner(System.in);
6.       System.out.print("Input a number in inches:");
7.       inch=sc.nextFloat();
8.       foot = inch/12.0f;//1 foot=12 inches
9.     cent = inch*2.54f;//1 inch=2.54 centimeters
10.     System.out.format("%-10s%-10s%-10s\n", "INCH","FOOT","CENTIMETER");
11.     System.out.format("%-10.3f%-10.3f%-10.3f\n",inch,foot,cent);

12.  }

13.}

Program Output
Input a number in inch: 12
INCH            FOOT            CENTIMETER
12.000            1.000            30.480

Code Explanation
1. Include the Scanner class. By including the Scanner class in the program, you will have nextFloat() method
to read a floating-pointer number from the keyboard.
2. Open MeasurementConverter class block.
3. Open the main method block. The Java program begins from the main method.
4. Declare local variable inch, foot, and cent that are used to store measurements in inch, foot, and centimeter.
5. Create Scanner object. The constructor of the Scanner class can wrap the System.in class to allow number input from keyboard.
6. Tell the user to input a number in inch.