w3resource

Temperature Conversion: Kotlin Program for Celsius to Fahrenheit and Vice Versa


Write a Kotlin program to convert temperature from Celsius to Fahrenheit and vice versa.


Sample Solution:

Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Command-Line Arguments.
  • Type Conversion.
  • Conditional Statements.
  • Temperature Conversion Formulas.
  • Error Handling.
  • String Interpolation.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Prompt for Input.
  • Validate the Option.
  • Request Temperature Input.
  • Create Conversion Functions.
  • Use a When Expression.
  • Display the Output.
  • Handle Invalid Input.
  • Test with Different Inputs.
  • Common Errors to Avoid:
    • Forgetting to validate input.
    • Misplacing operators in formulas.
    • Not handling invalid inputs gracefully.

Kotlin Code:

fun main(args: Array<String>) 
 {
    println("Choose an option:")
    println("1. Convert Celsius to Fahrenheit")
    println("2. Convert Fahrenheit to Celsius")
    val option = args[0].toIntOrNull()
    println("Choice = $option")
    if (option != null && (option == 1 || option == 2)) {
        println("Enter the temperature:")
        val temperature = args[1].toDoubleOrNull()

        if (temperature != null) {
            when (option) {
                1 -> {
                    val fahrenheit = celsiusToFahrenheit(temperature)
                    println("Temperature in Celsius: $temperature")
                    println("Temperature in Fahrenheit: $fahrenheit")
                }
                2 -> {
                    val celsius = fahrenheitToCelsius(temperature)
                    println("Temperature in Fahrenheit: $temperature")
                    println("Temperature in Celsius: $celsius")
                }
            }
        } else {
            println("Invalid temperature. Please enter a valid numeric value.")
        }
    } else {
        println("Invalid option. Please choose option 1 or 2.")
    }
}

fun celsiusToFahrenheit(celsius: Double): Double {
    return (celsius * 9 / 5) + 32
}

fun fahrenheitToCelsius(fahrenheit: Double): Double {
    return (fahrenheit - 32) * 5 / 9
}

Sample Output:

Choose an option:
1. Convert Celsius to Fahrenheit
2. Convert Fahrenheit to Celsius
Choice = 1
Enter the temperature:
Temperature in Celsius: 32.0
Temperature in Fahrenheit: 89.6
Choose an option:
1. Convert Celsius to Fahrenheit
2. Convert Fahrenheit to Celsius
Choice = 2
Enter the temperature:
Temperature in Fahrenheit: 89.6
Temperature in Celsius: 32.0

Explanation:

In the above exercise,

  • The user is prompted to choose an option by entering a number: 1 for converting Celsius to Fahrenheit, or 2 for converting Fahrenheit to Celsius.
  • The user's input is read using readLine() and converted to an Int using toIntOrNull().
  • The temperature input is read and converted to Double using toDoubleOrNull().
  • If the temperature input is valid, a when expression is used to handle the selected option:
  • Option 1: The celsiusToFahrenheit() function is called with the temperature value as an argument. The function converts Celsius to Fahrenheit using the formula: (celsius * 9 / 5) + 32.
  • Option 2: The fahrenheitToCelsius() function is called with the temperature value as an argument. The function converts Fahrenheit to Celsius using the formula: (fahrenheit - 32) * 5 / 9.
  • The converted temperature is then printed to the console using string interpolation.
  • If the temperature input or option is invalid (null or not within the specified range), error messages are displayed.

Go to:


PREV : Calculate circle area and perimeter.
NEXT : Kotlin Control Flow Exercises Home.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.