Kotlin calculator app development
Here's a simple example of a calculator app in Kotlin:
import java.util.Scanner
fun main(args: Array<String>) {
val reader = Scanner(System.`in`)
print("Enter two numbers: ")
// Reading values
val first = reader.nextDouble()
val second = reader.nextDouble()
print("Enter an operator (+, -, *, /): ")
val operator = reader.next()[0]
// Using when expression
val result = when (operator) {
'+' -> first + second
'-' -> first - second
'*' -> first * second
'/' -> first / second
else -> {
println("Error! operator is not correct")
0.0
}
}
// Output
println("$first $operator $second = $result")
}
This program takes two numbers as input and an operator, performs the operation based on the operator and outputs the result. The operator is selected using a when expression in Kotlin, which is similar to a switch statement in other languages.
import java.util.Scanner
fun main(args: Array<String>) {
val reader = Scanner(System.`in`)
var continueCalculating = true
while (continueCalculating) {
print("Enter two numbers: ")
// Reading values
val first = reader.nextDouble()
val second = reader.nextDouble()
print("Enter an operator (+, -, *, /, %, ^): ")
val operator = reader.next()[0]
// Using when expression
val result = when (operator) {
'+' -> first + second
'-' -> first - second
'*' -> first * second
'/' -> first / second
'%' -> first % second
'^' -> Math.pow(first, second)
else -> {
println("Error! operator is not correct")
0.0
}
}
// Output
println("$first $operator $second = $result")
println("Do you want to continue (Y/N)?")
continueCalculating = reader.next().first().toUpperCase() == 'Y'
}
}
This version of the calculator allows the user to perform multiple calculations and choose whether to continue or quit the program. It uses a while loop that continues as long as continueCalculating is true, and the user's choice to continue or quit is determined by their input to the program.
No comments:
Post a Comment