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.
- main() Function
The
main()
function is the entry point to a kotlin program.
fun main(vararg arg: String){
// calculator logic code
}
- 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(' ')
- 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.
- 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 asswitch case
in C/C++.
- 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
- 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
- readline()
var input: String? = readLine()
Reads a line of input from the standard input stream. To take the inputs from user
- Download
.jar
file from here - Open Command Prompt or Terminal.
cd
into that downloaded folder.- run
java -jar Calculator.jar
Code is written in clean manner as much as possible. Also outputed answers is improvised using
.toDoubleOrNull()
for long range value.
Download from here.