Example: Simple Calculator using switch Statement
import java.util.*
fun main(args: Array<String>) {
val reader = Scanner(System.`in`)
print("Enter two numbers: ")
// nextDouble() reads the next double from the keyboard
val first = reader.nextDouble()
val second = reader.nextDouble()
print("Enter an operator (+, -, *, /): ")
val operator = reader.next()[0]
val result: Double
when (operator) {
'+' -> result = first + second
'-' -> result = first - second
'*' -> result = first * second
'/' -> result = first / second
// operator doesn't match any case constant (+, -, *, /)
else -> {
System.out.printf("Error! operator is not correct")
return
}
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result)
}
When you run the program, the output will be:
Enter two numbers: 1.5 4.5 Enter an operator (+, -, *, /): * 1.5 * 4.5 = 6.8
The *
operator entered by the user is stored in the operator variable using the next()
method of Scanner
object.
Likewise, the two operands, 1.5 and 4.5 are stored in variables first and second respectively using the nextDouble()
method of Scanner
object.
Since, the operator *
matches the when condition '*':
, the control of the program jumps to
result = first * second;
This statement calculates the product and stores in the variable result and it is printed using the printf
statement.
Here's the equivalent Java code: Java Program to Make a Simple Calculator