Skip to content

Latest commit

 

History

History
147 lines (95 loc) · 3.59 KB

README.md

File metadata and controls

147 lines (95 loc) · 3.59 KB

Kotlin


Calculator Application

version open source kotlin build

My Application.

A very simple calculator application coded in kotlin programming language which takes inputs from user along with some arithmetic operator and perform further calculations.

I have also implemented some input validations :

  • input != null

    Null safety in conditions

  • input.isNotBlank()

    Returns true if this char sequence is not empty and contains some characters except of whitespace characters.


Kotlin Concepts Used

  1. main() Function

The main() function is the entry point to a kotlin program.

    fun main(vararg arg: String){
        // calculator logic code
    }
  1. Split String

input.split(' ') . Kotlin split string using delimiters as an parameter to split input from user into separate character.

    val values:List<String> = input.split(' ')
  1. if-else control flow
    if (values.size < 3){
        println("Invalid input. Expected: value + value. Received: $input")
    }else {
        // other code
        }

To check if user has giver the right amount of input.

  1. When Expression
val result = when (operator) {
            "+" -> lhs + rhs
            "-" -> lhs - rhs
             "*" -> lhs * rhs
            "/" -> lhs / rhs
            "%" -> lhs % rhs

            else -> throw IllegalArgumentException("Invalid operator: $operator")
            }

when operator is same as switch case in C/C++.

  1. Arrow (->) Operator
        "+" -> lhs + rhs
        "-" -> lhs - rhs
        "*" -> lhs * rhs
        "/" -> lhs / rhs
        "%" -> lhs % rhs

It will separate the condition and body of a when expression branch. If matches with inputed operator from user then it will perform that operation allocated to that operator like "+" -> lhs + rhs

  1. else-if operator
    val lhs = values[0].toDoubleOrNull() ?: throw IllegalArgumentException("Invalid input: ${values[0]}")
    val rhs = values[2].toDoubleOrNull() ?: throw IllegalArgumentException("Invalid input: ${values[1]}")

If input doesn't return Double or Null then it runs else part will get execute by throwing an IllegalArgumentException

  1. readline()
    var input: String? = readLine()

Reads a line of input from the standard input stream. To take the inputs from user


Setup

  • Download .jar file from here
  • Open Command Prompt or Terminal.
  • cd into that downloaded folder.
  • run java -jar Calculator.jar

Preview

preview


Code Improvements.

Code is written in clean manner as much as possible. Also outputed answers is improvised using .toDoubleOrNull() for long range value.


Certificate 🏆

30 Days of Kotlin

Download from here.


Thanks for reading out 😊