Kotlin: Create a Simple Calculator

1. Introduction

Building a simple calculator is a great way to get familiar with basic programming concepts such as taking user inputs, performing operations based on conditions, and displaying outputs. In this guide, we will walk you through how to create a basic calculator in Kotlin that can perform addition, subtraction, multiplication, and division.

2. Program Overview

Our calculator will:

1. Prompt the user to enter two numbers.

2. Prompt the user to select an operation (+, -, *, /).

3. Perform the chosen operation.

4. Display the result.

Let's dive into the code!

3. Code Program

fun main() {
    // Prompting the user to enter the first number
    print("Enter first number: ")
    val num1 = readLine()!!.toDouble()

    // Prompting the user to enter the second number
    print("Enter second number: ")
    val num2 = readLine()!!.toDouble()

    // Prompting the user to choose an operation
    print("Choose an operation (+, -, *, /): ")
    val operation = readLine()

    // Determine the operation and display the result
    val result = when (operation) {
        "+" -> num1 + num2
        "-" -> num1 - num2
        "*" -> num1 * num2
        "/" -> {
            if (num2 != 0.0) num1 / num2 else "Division by zero is undefined"
        }
        else -> "Invalid operation"
    }

    println("Result: $result")
}

Output:

Enter first number: 5
Enter second number: 3
Choose an operation (+, -, *, /): +
Result: 8.0

4. Step By Step Explanation

1. Taking Inputs:

  • We first prompt the user to input two numbers using the print function.
  • We then use readLine() to read the user input, followed by !! to assert that the input is non-null. Finally, toDouble() converts the String input to a Double data type.

2. Choosing an Operation:

  • The user is prompted to choose an operation from the available options.
  • We use a Kotlin when expression (similar to a switch-case in other languages) to determine the chosen operation.

3. Performing Calculations:

  • For addition, subtraction, and multiplication, the operations are straightforward.
  • For division, there's an extra check to ensure the denominator isn't zero. If it's zero, we display a message indicating that division by zero is undefined.
  • If an invalid operation symbol is entered, the program informs the user that the operation is invalid.

4. Displaying Result:

  • We use the println function to display the final result.

Through this simple calculator program, learners can understand how to take user inputs, use conditional statements, and display outputs in Kotlin.

Comments