无输入直接回车,没有退出循环?
来源:5-1 命令行计数器开发
慕运维0750787
2021-04-21 11:58:15
package chapter3
import java.lang.IllegalArgumentException
import java.lang.UnsupportedOperationException
fun main(args: Array<String>) {
while (true) {
println("请输入两个数的基本算式,以空格分隔。例如: 3 + 4")
val input = readLine()
if(input==null) break;
try {
// 以空隔分割输入input,转换成数组splits
val splits = input.trim().split(" ")//trim()去掉字符串前后的空格。这样字符串中间以空格分割
if (splits.size < 3) {
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)}")
println("$arg1 $op $arg2=${Operator(op).opFun(arg1, arg2)}")
}
} catch (e: NumberFormatException) {
println("你确定输入的是数字吗?数字与计算符之间请用空格隔开")
} catch (e: IllegalArgumentException)//参数非法
{
println("您确定输入的是三个参数吗?或者确定输入数字与计算符之间用空格分隔的吗?")
} catch (e: UnsupportedOperationException) {
print("请输入正确的运算符,只支持: + - * / %")
} catch (e: Exception) {
println("亲爱的用户,程序遇到了未知的异常,${e.message}")
}
println("再来一发?[Y]")
val cmd = readLine()
if (cmd == null || cmd.trim().toLowerCase() != "y") {
break
}
}
println("感谢使用我们的计算器!")
}
class Operator(op: String) {
val opFun: (left: Double, right: Double) -> Double//函数声明
init {
// 类初始化时判断运算符,实现opFun函数Lambda表达式的初始化
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)
}
}
}
// 传入opFun函数的参数
fun apply(left: Double, right: Double): Double {
return opFun(left, right)
}
}
老师,你好。程序运行后,我无输入,直接回车,没有退出循环。断点debug后如下:
inputs.size=1? 为什么不是0?
1回答
同学,你好!这里的条件不对哦
应该改为
if(input==null || input.equals("")) break;
祝:学习愉快!
相似问题