我有一个 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.readLine
或 println(... )
。这真的是同一个问题。在测试环境中,您如何向这样的程序提供输入?
我建议看一下这个 excellent example (在 this video by John De Goes 中解释)您的确切 问题,以函数式方式解决。该程序的最终结果可能对您的应用程序来说有点矫枉过正,所显示的其中一个中间程序可能是您的完美示例。我不建议为您的原始问题寻找真正的答案,而是您应该重构程序,以便您不需要找到该问题的答案。
关于linux - 如何将多行粘贴到 scala stdIn 进程的命令行提示符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681026/