Java Programming | Length Conversion

Introduction

This is a tutorial to convert length from one unit to other. The program takes the input of length in one unit and converts it into other and prints it. The program is extendable. Go enjoy the program. Lets begin……..

Program to convert meter to kilometer.


//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class LengthConversion {
//void main
public static void main (String[] args)
{
//declare float
float to,from;
//print message
System.out.println("Enter Length in meter:");
//Take input
Scanner input = new Scanner(System.in);
//calculate
from = input.nextFloat();
to = from/1000;
//print the average
System.out.println("Length in kilometer = "+to);
}
}

Output

Enter Length in meter:
500
Length in kilometer = 0.5

Program to convert meter to centimeter.

[code language=”java”]
//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class LengthConversion {
//void main
public static void main (String[] args)
{
//declare float
float to,from;
//print message
System.out.println(“Enter Length in meter:”);
//Take input
Scanner input = new Scanner(System.in);
//calculate
from = input.nextFloat();
to = from*100;
//print the average
System.out.println(“Length in centimeter = “+to);
}
}
[/code]

Output

Enter Length in meter:
0.12
Length in centimeter = 12.0

How it works

  1. The program prints the message to enter length.
  2. The user enters length.
  3. Length is converted.
  4. The converted length is printed.

Extending it

The Program can be extended by adding more unit to conversion and by adding their Conversion formula for other unit and more variables can be added to program to convert multiple lengths. Like wise you can also use following unit for conversion :-

  • nanometer
  • picometer
  • millimeter
  • centimeter
  • meter
  • kilometer
  • terameter

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter length.
  5. Declare input as Scanner.
  6. Take the length and save it in variable.
  7. Convert length and save it in other variable.
  8. Add system.out.println() function to print the converted length.

At the end.

You learnt creating the Java program for Length conversion. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: