java 代码如果要实现的话 代码量更多些。
下面直接看kotlin的。
package com.yzdzy.kotlin.calc
fun main(args: Array<String>) {
println("请输入算是 列如 3 + 4")
val input = readLine()
if (input != null) {
val splits = input.split(" ")
val arg1 = splits[0].toDouble()
val op = splits[1]
val arg2 = splits[2].toDouble()
print("$arg1 $op $arg2 = ${Operator(op).apply(arg1,arg2)}")
}
}
class Operator(op: String) {
val opFun: (left: Double, right: Double) -> Double
init {
opFun = when (op) {
"+" -> { l, r -> l + r }
"-" -> { l, r -> l - r }
"*" -> { l, r -> l * r }
"/" -> { l, r -> l / r }
"%" -> { l, r -> l % r }
else -> {
throw UnsupportedOperationException(op)
}
}
}
fun apply(left: Double, right: Double): Double {
return opFun(left,right)
}
}
输出
请输入算是 列如 3 + 4
3 + 4
3.0 + 4.0 = 7.0
优化改进成一直运算。
package com.yzdzy.kotlin.calc
fun main(args: Array<String>) {
while (true) {
println("请输入算是 列如 3 + 4")
val input = readLine() ?: break
val splits = input.split(" ")
val arg1 = splits[0].toDouble()
val op = splits[1]
val arg2 = splits[2].toDouble()
println("$arg1 $op $arg2 = ${Operator(op).apply(arg1, arg2)}")
println("再来一次?[Y]")
val cmd = readLine()
if (cmd == null || cmd.toLowerCase() != "y") {
break
}
}
}
class Operator(op: String) {
val opFun: (left: Double, right: Double) -> Double
init {
opFun = when (op) {
"+" -> { l, r -> l + r }
"-" -> { l, r -> l - r }
"*" -> { l, r -> l * r }
"/" -> { l, r -> l / r }
"%" -> { l, r -> l % r }
else -> {
throw UnsupportedOperationException(op)
}
}
}
fun apply(left: Double, right: Double): Double {
return opFun(left, right)
}
}
package com.yzdzy.kotlin.calc
fun main(args: Array<String>) {
while (true) {
println("请输入算是 列如 3 + 4")
try {
val input = readLine() ?: break
val splits = input.trim().split(" ")
if (splits.size < 2) {
throw IllegalArgumentException("参数个数不对")
}
val arg1 = splits[0].toDouble()
val op = splits[1]
val arg2 = splits[2].toDouble()
println("$arg1 $op $arg2 = ${Operator(op).apply(arg1, arg2)}")
} catch (e: NumberFormatException) {
println("您确定输入的是数字吗")
} catch (e: IllegalArgumentException) {
println("您确定输入是三个参数吗。您确定是三个空格分割的嘛")
} catch (e: Exception) {
println("未知错误${e.message}")
}
println("再来一次?[Y]")
val cmd = readLine()
if (cmd == null || cmd.toLowerCase() != "y") {
break
}
}
println("感谢您使用我们的计算器")
}
class Operator(op: String) {
val opFun: (left: Double, right: Double) -> Double
init {
opFun = when (op) {
"+" -> { l, r -> l + r }
"-" -> { l, r -> l - r }
"*" -> { l, r -> l * r }
"/" -> { l, r -> l / r }
"%" -> { l, r -> l % r }
else -> {
throw UnsupportedOperationException(op)
}
}
}
fun apply(left: Double, right: Double): Double {
return opFun(left, right)
}
}