English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program using switch ... case to make a simple calculator

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to make a simple calculator using the when expressions in Kotlin. This calculator will be able to perform addition, subtraction, multiplication, and division on two numbers.

Example: A simple calculator using the switch statement

import java.util.*
fun main(args: Array<String>) {
    val reader = Scanner(System.`in`)
    print("Enter two numbers: ")
    //nextDouble() reads the next double from the keyboard
    val first = reader.nextDouble()
    val second = reader.nextDouble()
    print("Enter an operator (+, -, *, /: )
    val operator = reader.next()[0]
    val result: Double
    when (operator) {
        '+' -> result = first + second
        '-' -> result = first - second
        '*' -> result = first * second
        '/' -> result = first / second
        //The operator does not match any case constant (+, -, *, /)
        else -> {
            System.out.printf("Error! The operator is incorrect")
            return
        }
    }
    System.out.printf("%.2f.1f %c %.2f.1f = %.2f.1f", first, operator, second, result)
}

When running this program, the output is:

Enter two numbers: 1.5
4.5
Enter an operator (+, -, *, /) *
1.5 * 4.5 = 6.8

User input's * The operator is used with the next() method of the Scanner object, stored in the operator variable.

Similarly, two operands1.5and4.5are stored in the variables first and second respectively, using the nextDouble() method of the Scanner object.

because, the operator * Matching the when condition '*':, program control jumps to the following:',

result = first * second;

This statement calculates the product and stores it in the variable result, and uses the printf statement to print.

The following is the equivalent Java code:Java Program to Create a Simple Calculator

Comprehensive Collection of Kotlin Examples