首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Scala :当Ctrl-d按下时如何停止程序

Scala :当Ctrl-d按下时如何停止程序
EN

Stack Overflow用户
提问于 2017-02-22 12:42:35
回答 2查看 872关注 0票数 1

如何通过按Ctrl来停止类似REPL的控制台应用程序,而不等待用户输入Ctr-d然后进入?

下面是一个代码示例:

代码语言:javascript
复制
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。

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

代码语言:javascript
复制
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)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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,以满足我们的需要。完整的工作示例:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-02-22 14:24:48

对代码的小修改

代码语言:javascript
复制
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如下所示。否则,您的示例将按预期工作。

代码语言:javascript
复制
def isExit(s: String): Boolean = s.headOption.map(_.toInt) == Some(4) || s == "exit"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42391827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档