michelpm
michelpm

Reputation: 1845

How to use java.util.Scanner from scala

I tried to use java.util.Scanner from scala:

val scanner = new java.util.Scanner(System.in)
val line = scanner.readLine()
println(line)

Either by pasting on scala REPL or by running scala file.scala, I get this:

:2: error: value readLine is not a member of java.util.Scanner
val line = scanner.readLine()

What am I missing?

Upvotes: 1

Views: 7165

Answers (2)

maasg
maasg

Reputation: 37435

The easiest way seems to be using JavaConverters to use the Scanner as an Iterator:

import scala.collection.JavaConverters._
...
val input = new Scanner(System.in).asScala
input.head // first element
val asList = input.toList // scala list 

Upvotes: 4

Brian
Brian

Reputation: 20285

java.util.Scanner has no readLine try nextLine.

scala> val scanner = new java.util.Scanner(System.in)
scanner: java.util.Scanner = java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]

scala> val line = scanner.nextLine()
line: String = foo

Upvotes: 6

Related Questions