2017-02-22 61 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