ssk
ssk

Reputation: 55

How to take input with white spaces and append list in scala?

I have a scenario where I have to take N input with white spaces from the user and append inputs into the list to find min or max out of the list. Input for list size 4 Now take 4 inputs like 3 5 6 8. I don't want to press Enter to append list!

println("Enter List size ")
   val list = new ListBuffer[Int]() 
   val size:Int=scala.io.StdIn.readInt()
    for(x<-1 to size) {
      val input = scala.io.StdIn.readInt()
      list += input

    }
    println(list.max) 

Upvotes: 0

Views: 167

Answers (2)

jwvh
jwvh

Reputation: 51271

Read N integers from StdIn while allowing for faulty user input.

def getNInts(n: Int): List[Int] =
  List.unfold(0){cnt =>
    Option.when(cnt < n){
      val lst = io.StdIn.readLine(s"${n-cnt} Integers: ")
                  .split("\\s+").flatMap(_.toIntOption)
      (lst, cnt + lst.length)
    }
  }.flatten.take(n)

REPL testing:

scala> val ns = getNInts(7)
7 Integers: 11   2       3 44
3 Integers: five 555 V
2 Integers: 6 7 8 9
val ns: List[Int] = List(11, 2, 3, 44, 555, 6, 7)

Upvotes: 2

Slightly modified from @jwvh comment to repeat until the user provides 4 numbers.

def read4Numbers(): (Int, Int, Int, Int) = {
  val inputs =
    io
      .StdIn
      .readLine("Enter 4 elements: ")
      .split("\\s+")
      .iterator
      .flatMap(_.toIntOption)
      .toList

  inputs match {
    case n1 :: n2 :: n3 :: n4 :: Nil =>
      (n1, n2, n3, n4)

    case _ =>
      read4Numbers()
}

(btw, I am on cellphone so if I have some typos please edit the answer)

Upvotes: 2

Related Questions