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

时间:2015-06-14 15:39:21

标签: file scala input

我的程序有很多不同的功能,其中一个是命令“load”。 一旦用户输入“load”输入,他就可以加载到txt文件中...... 问题是,我的命令不仅仅是“加载”字本身,例如“load numbers.txt”或“load data.txt”

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

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!")

所以我的函数是ProgramSelector,如果输入是加载的话我只会创建一个if语句...

1 个答案:

答案 0 :(得分:1)

我试图让这更通用一点。

为了说明这有什么用处,我还创建了另一个命令,你可以称之为“add 1 2”,它将打印添加两个整数的总和。

如果您认真制作CLI交互式应用程序,我建议您查看如何在sbt之上创建自己的交互式shell的here

val loadCommand = """load (.*)""".r
val helpCommand = """help.*""".r
val exitCommand = """exit.*""".r
val addCommand = """add\s+(\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()