Distance Calculation in Java


The distance between two cities (in km.) is input through the keyboard. Write a program to convert and print this distance in meters, feet, inches and centimeters.

  • The program starts by importing the java.util.Scanner package, which allows the user to input data into the program.
  • Then, it declares five variables of float data type - m (meters), km (kilometers), cm (centimeters), i (inches), and ft (feet).
  • The program then prompts the user to enter the distance in kilometers by displaying the message "Enter the Kilometer :". It takes the input using the Scanner object and stores it in the km variable.
  • Next, the program calculates the m value by multiplying the km value with 1000 (since 1 kilometer = 1000 meters).
  • The program then calculates the cm value by multiplying the m value with 100 (since 1 meter = 100 centimeters).
  • Next, the program calculates the i value by dividing the cm value by 2.54 (since 1 inch = 2.54 centimeters).
  • Finally, the program calculates the ft value by dividing the i value by 12 (since 1 foot = 12 inches).

Overall, this program is a basic example of how Java can be used to perform simple unit conversions and input/output operations.


Source Code

import java.util.Scanner;
class Distance
{
	public static void main(String arga[])
	{
		float m,km,cm,i,ft;
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the Kilometer :");
		km = input.nextFloat();
		m = km*1000;
		cm = m*100;
		i = cm/2.54f;
		ft = i/12;
		System.out.println("Kilometer : "+km);
		System.out.println("Meters : "+m);
		System.out.println("Centimeters : "+cm);
		System.out.println("Inches : "+i);
		System.out.println("Feet : "+ft);
	}
}

Output

Enter the Kilometer :
23.4
Kilometer : 23.4
Meters : 23400.0
Centimeters : 2340000.0
Inches : 921259.9
Feet : 76771.66