1

I have a number of lines as input and want to read and print the exact same thing. The problem is I don't know how! (readLine) The input comes from a user typing in terminal.

the first integer is the number of lines in total!

input:

4
word
localization
internationalization

output:

word
localization
internationalization
4
  • the input comes from a user typing into a terminal. Beacuse readLine gets the input Commented Nov 1, 2020 at 8:50
  • 1
    readLine does read a line from stdin. What didn't work about it? Commented Nov 1, 2020 at 8:57
  • I want the program to read multiple lines simultaneously! readLine reads one line only Commented Nov 1, 2020 at 9:00
  • 2
    2 options: call readLine several times, or write your own utility based on InputStream Commented Nov 1, 2020 at 11:27

2 Answers 2

2

Something like

// default condition: string is not empty, not inclusive! 
class TermLines (cond: (String => Boolean) = _ != "") extends Iterator[String] { 
  var s = readLine; 
  def hasNext = cond(s); 
  def next = { var r = s; s = readLine; r } 
} 

Then call it like

println((new TermLines).toVector.mkString("\n")) // till empty

or

println(new TermLines(_ != ".").toVector.mkString("\n")) // till last is dot
Sign up to request clarification or add additional context in comments.

1 Comment

this is beautiful
-1

Solved!

import scala.io.StdIn

object Solution extends App
{
    val numOfLines = StdIn.readInt()
    def words: Seq[String] = for (_ <- 1 to numOfLines) yield StdIn.readLine()
    def sort = words.map
    {
        case word => word
    }
    sort.foreach(println)
}

3 Comments

The .map() call doesn't do anything so sort is exactly the same as words.
That's not the whole code. I cut the code. case word if word.length > 10 => (s"${word.head}${(word.length - 2).toString}${word.last}") case word => word. But you are RIGHT!
Two sets of parens () are unneeded and the .toString is unneeded. The use of readInt() is dangerous. Glad it works for you but it's not a very good solution for the actual question as posted.

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.