1
  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

It gives this message E:\Scala>scala HelloWord.scala Enter some numbers and press ctrl-c 1 2 3 Terminate batch job (Y/N)?

0

3 Answers 3

2

Additional observations, note trait App to make an object executable, hence not having to declare a main(...) function, for instance like this,

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.

Also note objects and classes are capitalized, hence instead of object sum by convention we write object Sum.

Sign up to request clarification or add additional context in comments.

1 Comment

@elm- While I am running the code you have sent is not printing anything
2

You can also use an external API. I really like scallop API

Comments

1

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.

2 Comments

Thanks its working. I am using in windows 7 So for input stream Ctrl + C is working
-Accepted your answer. Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.