Java Program to convert Miles to Kilometer

Program

import java.util.*;
class ConvertMilesToKilometer {
    public static void main(String[] args) {
        float kilometer, miles, conv_factor;
        System.out.println("Enter the miles to convert:");
        Scanner sc = new Scanner(System.in);
        miles = sc.nextFloat();
        conv_factor = 1.609344 f;
        kilometer = miles * conv_factor;
        System.out.println("Value in Kilometers:\t" + kilometer);
        sc.close();
    }
}

The program declares three float variables: kilometer, miles, and conv_factor. miles stores the value entered by the user in miles. kilometer stores the equivalent value in kilometers. conv_factor holds the conversion factor from miles to kilometers, which is approximately 1.609344 (1 mile = 1.609344 kilometers).

The program prompts the user to enter the value in miles using System.out.println("Enter the miles to convert:");. It then reads the input using a Scanner object sc, and stores the value in the miles variable using miles = sc.nextFloat();. The program calculates the equivalent value in kilometers by multiplying the input value in miles with the conversion factor (conv_factor). This calculation is performed using the expression kilometer = miles * conv_factor;.

The program prints the converted value in kilometers to the console using System.out.println("Value in Kilometers:\t" + kilometer);.

Consider an example to illustrate step by step process to convert Miles to Kilometers:

If the user enters 10 miles:

miles will be 10. The program calculates kilometer as 10 * 1.609344, which equals approximately 16.09344 kilometers. It then prints "Value in Kilometers: 16.09344" to the console.

Output

Enter the miles to convert:
2000
Value in Kilometers: 3218.688

Tags: