linux - 如何将多行粘贴到 scala stdIn 进程的命令行提示符?

标签 linux scala command-line stdin

我有一个 scala 程序在循环中提示用户输入,比如 输入名字: 输入年龄: 继续吗?:

如何准备多个用户输入的字符串并将其复制并粘贴一次到提示中以模拟用户输入多个用户信息。

我试过 john\n26\nc\nlucy\22\c...

val acctList = ListBuffer.empty[UserInfo]
breakable {
  while (true) {
    try {
      println(s"enter name: ")
      val myName = scala.io.StdIn.readLine
      val stdIn = System.console()
      println(s"enter age for $myName")
      val myAge = scala.io.StdIn.readLine
      val acct = UserInfo(myName, myAge)
      acctList += acct
      println(s"enter c to continue: ")
      val cont = scala.io.StdIn.readLine
      if (cont != "c") break
    }
    catch {
      case e: NumberFormatException => println("number format exception caught:" + e.toString)
      case e: StringIndexOutOfBoundsException => println("string index out of range:" + e.toString)
      case e: Exception => println("exception caught:" + e.toString)
    }
  }
}

将“John\n26\nc\nLucy\n22\nx”粘贴到第一个提示中,我应该能够在 acctList 中读取为 ({"John", 26}, {Lucy, 22})

最佳答案

我敢肯定,几乎所有编程专业的学生都曾遇到过这个问题。您问题的本质似乎是“如何在我的程序中模拟副作用(本例中的输入/输出)?”如果您的代码调用 database.insert(...) 而不是 scala.io.StdIn.readLineprintln(... )。这真的是同一个问题。在测试环境中,您如何向这样的程序提供输入?

我建议看一下这个 excellent example (在 this video by John De Goes 中解释)您的确切 问题,以函数式方式解决。该程序的最终结果可能对您的应用程序来说有点矫枉过正,所显示的其中一个中间程序可能是您的完美示例。我不建议为您的原始问题寻找真正的答案,而是您应该重构程序,以便您不需要找到该问题的答案。

关于linux - 如何将多行粘贴到 scala stdIn 进程的命令行提示符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681026/

相关文章:

scala - Spark-scala : Check whether a S3 directory exists or not before reading it

mysql - 如何显示所有用户定义的变量(MySQL)

android - 如何从命令行发送 String[] Intent 额外值?

linux - tar 存档 : How reliable is append?

linux - 如何调试导致 "emacs24.4 --daemon"不返回shell的init文件?

c# - Linux/C++ 程序员到 C#/Windows 程序员

java - 在windows 8命令行上编译Junit报错

linux - 用于检查文件中是否存在段落/行流的 Shell 脚本

scala - `maxResultSize` 包含什么以及所有驱动程序内存在哪里

scala - akka actor适用于搜索等在线服务系统吗?