Kotlin program to convert distance Miles to KM and KM to Miles

Kotlin | Distance Unit Converter: Here, we are going to learn how to convert distance (Miles to KM and KM to Miles) in Kotlin programming language? Submitted by IncludeHelp, on April 16, 2020

Problem statement

Here, we will create a distance convertor i.e. a program to convert distance Miles to KM and KM to Miles in Kotlin.

The conversions use direct conversion formula,

miles = km/1.609
km = miles*1.609

Example:

Input: 
miles = 2
km = 2

Output:
km = 3.218
miles = 1.2430080795525171

Program to convert distance Miles to KM and KM to Miles in Kotlin

package com.includehelp.basic

import java.util.*

/**
 * Method to get distance in miles and convert into Kilometers
 * @param miles
 * @return
 */
fun convertIntoKms(miles: Double): Double {
    return 1.609 * miles
}

/**
 * Method to get distance in km and convert into miles
 * @param km
 * @return
 */
fun convertIntoMiles(km: Double): Double {
    return km / 1.609
}

// Main Method Entry Point of Program
fun main(args: Array<String>) {
    try {
        val sc = Scanner(System.`in`)
        
        //Input Distance in Miles
        println("Enter Distance in Miles  : ")
        val miles: Double = sc.nextDouble()
        
        println("$miles Miles equal to :  ${convertIntoKms(miles)}  KMs")
        
        //Input Distance in kms
        println("Enter Distance in Km  : ")
        val kms: Double = sc.nextDouble()
        
        println("$kms   KMs equal to   :  ${convertIntoMiles(kms)}  Miles")
    } catch (E: Exception) {
        System.err.println("Exception : " + E.message)
    }
}

Output

Run 1:
Enter Distance in Miles  :
2
2.0 Miles equal to :  3.218  KMs
Enter Distance in Km  :
2
2.0   KMs equal to   :  1.2430080795525171  Miles
-----
Run 2:
Enter Distance in Miles  :
4
4.0 Miles equal to :  6.436  KMs
Enter Distance in Km  :
12
12.0   KMs equal to   :  7.458048477315103  Miles

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.