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
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.
7. Receive the number input.
8. Convert the number from inch to foot.
9. Convert the number from inch to centimeter.
10. Display heading text. Each heading column text is displayed ten characters wide and left aligned.
11. Display the result in inch, foot, and centimeter. Each floating-point number is ten characters wide, left aligned, and shows three decimal places.
Note: \n is a special character that is used to output a new line on the screen.
No comments:
Post a Comment