Scala:通过输入加载不同的文件



我的程序有很多不同的函数,其中之一就是命令"load"。一旦用户输入输入"加载",他就可以加载到 txt 文件中......问题是,我的命令不仅是"加载"一词本身,例如"加载数字.txt"或"加载数据.txt"

现在我想打开这些位于我的 PC 上的文本文件,但我需要文件名,命令前面没有"加载"。如何仅从整个输入行中获取名称?

def ProgramSelector() {
var endProgram = false
while (!endProgram) {
  val userSelection = scala.io.StdIn.readLine("There is no transfer data available yet, please use the 'load' command to initialize the application!nEnter your command or type 'help' for more information:")
  if (userSelection == "help")
    println("some help text here")
else if (userSelection == "load")
  //else if (userSelection == "3")
    //exerciseThree()
  //else if (userSelection == "4")
    //exerciseFour()
  //else if (userSelection == "5")
    //exerciseFive()
  //else if (userSelection == "6")
    //exerciseSix()
  //else if (userSelection == "7")
    //exerciseSeven()
  //else if (userSelection == "8")
    //exerciseEight()
  else if (userSelection == "exit")
    endProgram = true
  else
    println("Invalid command!")

所以我有我的函数程序选择器,如果输入加载,我只做一个 if 语句......

我试图让它更通用一点。

为了说明这如何提供帮助,我还创建了另一个命令,您可以将其称为"add 1 2",它将打印两个整数相加的总和。

如果你真的想做一个CLI交互式应用程序,我建议你在这里看看如何在sbt之上制作自己的交互式shell。

val loadCommand = """load (.*)""".r
val helpCommand = """help.*""".r
val exitCommand = """exit.*""".r
val addCommand = """adds+(d+)s+(d+)""".r
val PromptMsg = "There is no transfer data available yet, please use the 'load' command to initialize the application!nEnter your command or type 'help' for more information: "
def programSelector() {
    var endProgram = false
    val fileKeeper = new scala.collection.mutable.HashSet[String]()
    while (!endProgram) {
        val userSelection = scala.io.StdIn.readLine(PromptMsg)
        userSelection match {
            case loadCommand(file) => 
                println(s"Adding file $file")
                fileKeeper add file
                println(s"Files so far: $fileKeeper")
            case helpCommand() => 
                println("some help text here")
            case exitCommand() => 
                endProgram = true
            case addCommand(a,b) => 
                val sum = a.toInt + b.toInt
                println(s"Sum=$sum") 
            case _ => 
                println("Invalid command!")
        }   
    }
}

programSelector() 

相关内容

  • 没有找到相关文章

最新更新