简体   繁体   English

如何通过命令行在scala中传递输入

[英]How to pass input in scala through command line

  import scala.io._    

  object Sum {    
     def main(args :Array[String]):Unit = {    

      println("Enter some numbers and press ctrl-c")

     val input = Source.fromInputStream(System.in)

     val lines = input.getLines.toList

     println("Sum "+sum(lines))

   }

   def toInt(in:String):Option[Int] =

      try{

        Some(Integer.parseInt(in.trim))

      }

      catch    {
       case e: NumberFormatException => None    
   } 

   def sum(in :Seq[String]) = {

     val ints = in.flatMap(s=>toInt(s))

      ints.foldLeft(0) ((a,b) => a +b)

     } }

I am trying to run this program after passing input I have press ctrl + c but我试图在传递输入后运行这个程序我按下了 ctrl + c 但是

It gives this message E:\\Scala>scala HelloWord.scala Enter some numbers and press ctrl-c 1 2 3 Terminate batch job (Y/N)?它给出了这条消息 E:\\Scala>scala HelloWord.scala 输入一些数字并按 ctrl-c 1 2 3 Terminate batch job (Y/N)?

Additional observations, note trait App to make an object executable, hence not having to declare a main(...) function, for instance like this,额外的观察,注意trait App使对象可执行,因此不必声明main(...)函数,例如这样,

object Sum extends App {
  import scala.io._
  import scala.util._

  val nums = Source.stdin.getLines.flatMap(v => Try(v.toInt).toOption)
  println(s"Sum: ${nums.sum}")
}

Using Try , non successful conversions from String to Int are turned to None and flattened out.使用Try ,从StringInt不成功转换将变为None并变平。

Also note objects and classes are capitalized, hence instead of object sum by convention we write object Sum .还要注意对象和类是大写的,因此按照约定,我们写object Sum而不是object sum

You can also use an external API.您还可以使用外部 API。 I really like scallop API我真的很喜欢扇贝 API

Try this piece of code.试试这段代码。 It should work as intended.它应该按预期工作。

object Sum {
    def main(args: Array[String]) {
        val lines = io.Source.stdin.getLines
        val numbers = lines.map(_.toInt)
        println(s"Sum: ${numbers.sum}")
    }
}

Plus, the correct shortcut to end the input stream is Ctrl + D .另外,结束输入流的正确快捷方式是Ctrl + D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM