Java Program to Convert Miles To Kilometers And Kilometers To Miles

In the previous article, we have seen Java Program to Convert a Negative Number to a Positive Number

In this article we are going to see how we can create a convertor to convert miles to kilometers and kilometers to miles in java.

Java Program to Convert Miles To Kilometers And Kilometers To Miles

Approach:

  • Ask the user to pick the conversion mode i.e.from km to miles or vice versa.
  • Use a switch case to pickthe conversion mode
  • Multiply miles with 1.60934 to convert it into km or divide km by 1.60394 to get miles.
  • Print the total result with both miles and km.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Class to take input
        Scanner scan = new Scanner(System.in);
        // Asks the user to pick the conversion mode
        System.out.print("Enter k to convert km to miles and m to convert miles to km :");
        char ch = scan.nextLine().charAt(0);
        double m = 0,k = 0;
        // Seitch case to choose the conversion mode
        switch(ch)
        {
            case 'm' :  System.out.println("Enter miles");
                        // Takes user input
                        m =scan.nextDouble();
                        k = 1.60934 * m;
                        break;

            case 'k' :  System.out.println("Enter miles");
                        // Takes user input
                        k =scan.nextDouble();
                        m = k / 1.60934 ;
                        break;
        }
        // Displays the conversion result
        System.out.println("In miles "+m+" and in km "+k);
    }
}

Output:

Enter k to convert km to miles and m to convert miles to km :m
Enter miles
25
In miles 25.0 and in km 40.2335

Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

Related Java Programs: