2017-02-22 74 views
1

如何停止按Ctrl-d一个REPL般的控制台应用程序,而无需等待用户输入CTR-D,然后输入一个程序?斯卡拉:如何停止的时候按Ctrl-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 d。

编辑:完整的源代码来运行它:

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) 
      } 
     } 
    } 
} 

有了这个,我上了s.headOption一个NullPointerException

回答

1

好,如 Read Input until control+d 说,按Ctrl-d按键冲线到JVM。 如果写东西就行,它会被发送(仅后连续两次CTRL-d,我不知道为什么),否则io.StdIn.readLine将收到流字符的结束,并将返回null,在斯卡拉DOC表示http://www.scala-lang.org/api/2.12.0/scala/io/StdIn $#的.html的readLine():字符串

知道了这一点,我们可以通过一个简单的s == null更换s.headOption...符合我们的需求。 全部工作实施例:

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) 
      } 
     } 
    } 
} 
0

稍作修改的代码(因为空S)

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" 
+0

的's'仍然'null'上'isExit'上的CTRL-d的值,所以仍存在的NullPointerException。 – aaaaaaa