原文: https://www.programiz.com/kotlin-programming/examples/calculator-when
在此程序中,您将学习使用 Kotlin 中的when表达式制作一个简单的计算器。 该计算器将能够对两个数字进行加,减,乘和除运算。
示例:使用switch语句的简单计算器
import java.util.*fun main(args: Array<String>) {val reader = Scanner(System.`in`)print("Enter two numbers: ")// nextDouble() reads the next double from the keyboardval first = reader.nextDouble()val second = reader.nextDouble()print("Enter an operator (+, -, *, /): ")val operator = reader.next()[0]val result: Doublewhen (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)}
运行该程序时,输出为:
Enter two numbers: 1.54.5Enter an operator (+, -, *, /): *1.5 * 4.5 = 6.8
使用Scanner对象的next()方法,将用户输入的*运算符存储在operator变量中。
同样,使用Scanner对象的nextDouble()方法,将两个操作数 1.5 和 4.5 分别存储在变量first和second中。
由于运算符*匹配何时条件'*':,因此程序控制跳至
result = first * second;
该语句计算产品并将结果存储在变量result中,并使用printf语句进行打印。
以下是等效的 Java 代码:制作简单计算器的 Java 程序
