Kotlin Program to Make a Simple Calculator Using When

In this post, you’ll learn to make a simple calculator using When in Kotlin.

Example: Make a Simple Calculator Using When

import java.util.Scanner

fun main(){

   val input = Scanner(System.`in`)

    print("Enter first Number: ")
    val firstNumber = input.nextInt()

    print("Enter second Number: ")
    val secondNumber = input.nextInt()

    print("Enter Action (+, -, *, /, %): ")
    val choice  = input.next()[0]

    val result  = when(choice){
        '+' -> firstNumber  + secondNumber
        '-' -> firstNumber  - secondNumber
        '*' -> firstNumber  * secondNumber
        '/' -> firstNumber  / secondNumber
        '%' -> firstNumber  % secondNumber
        else -> {
            System.err.println("Not a valid operation")
            return
        }
    }
    print(result)
}

Techpass Master

Techpass Master is a website for free Android App Development, Java, Kotlin, Jetpack Compose, Firebase, & other tech tips & tricks tutorials. We focus on posting the article at Android App Development. Apart from App development tutorials, we also occasionally post other technology tips and tricks, which can be very helpful for you. Stay tuned with Techpass Master for more updates.
View All Articles

Leave a Reply

Your email address will not be published.