如何通过按Ctrl来停止类似REPL的控制台应用程序,而不等待用户输入Ctr-d然后进入?
下面是一个代码示例:
def isExit(s: String): Boolean = s.head.toInt == 4 || s == "exit"
def main(args: Array[String]) = {
val continue: Boolean = true
while(continue){
println "> "
io.StdIn.readLine match {
case x if isExit(x) => println "> Bye!" ; continue = false
case x => evaluate(x)
}
}
}s.head.toInt == 4将测试输入行的第一个字符是否为ctrl。
编辑:运行它的完整源代码:
object Test {
def isExit(s: String): Boolean = s.headOption.map(_.toInt) == Some(4) || s == "exit"
def evaluate(s: String) = println(s"Evaluation : $s")
def main(args: Array[String]) = {
var continue = true
while(continue){
print("> ")
io.StdIn.readLine match {
case x if isExit(x) => println("> Bye!") ; continue = false
case x => evaluate(x)
}
}
}
}有了这个,我在NullPointerException上得到了一个s.headOption (因为null s)
发布于 2017-02-22 15:51:14
好的,正如在Read Input until control+d中所说,Ctrl按键将行刷新到JVM中。如果在行上写了什么,它将被发送(只在两个连续的ctrl-d之后,我不知道为什么),否则io.StdIn.readLine将接收流字符的结束并返回null,如scala doc http://www.scala-lang.org/api/2.12.0/scala/io/StdIn$.html#readLine():String中所示。
知道了这一点,我们可以用一个简单的s.headOption...来代替s == null,以满足我们的需要。完整的工作示例:
object Test {
def isExit(s: String): Boolean = s == null || s == "exit"
def evaluate(s: String) = println(s"Evaluation : $s")
def main(args: Array[String]) = {
var continue = true
while(continue){
print("> ")
io.StdIn.readLine match {
case x if isExit(x) => println("Bye!") ; continue = false
case x => evaluate(x)
}
}
}
}发布于 2017-02-22 14:24:48
对代码的小修改
def main(args: Array[String]) = {
var continue: Boolean = true // converted val to var
while(continue){
println("> ")
io.StdIn.readLine match {
case x if isExit(x) => println("> Bye!") ; continue = false
case x => evaluate(x)
}
}
}您的isExit方法没有处理读取行可能为空的条件。因此,修改后的isExit如下所示。否则,您的示例将按预期工作。
def isExit(s: String): Boolean = s.headOption.map(_.toInt) == Some(4) || s == "exit"https://stackoverflow.com/questions/42391827
复制相似问题