86

I want to take input from the user. Can you please tell me how to ask for user input as a string in Scala?

3
  • 6
    val input = readLine("prompt> ") Commented Feb 20, 2011 at 7:32
  • See Console on Scaladoc. Commented Feb 20, 2011 at 14:46
  • Direct use of readLine() is deprecated. Instead, import the one in the StdIn: import scala.io.StdIn.readLine; Commented Sep 9, 2015 at 6:15

10 Answers 10

131

In Scala 2.11 use

scala.io.StdIn.readLine()

instead of the deprecated Console.readLine.

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

Comments

29

Here is a standard way to read Integer values

val a = scala.io.StdIn.readInt()
println("The value of a is " + a)

similarly

def readBoolean(): Boolean

Reads a Boolean value from an entire line from stdin.

def readByte(): Byte

Reads a Byte value from an entire line from stdin.

def readChar(): Char

Reads a Char value from an entire line from stdin.

def readDouble(): Double

Reads a Double value from an entire line from stdin.

def readFloat(): Float

Reads a Float value from an entire line from stdin.

def readInt(): Int

Reads an Int value from an entire line from stdin.

def readLine(text: String, args: Any*): String

Prints formatted text to stdout and reads a full line from stdin.

def readLine(): String

Reads a full line from stdin.

def readLong(): Long

Reads a Long value from an entire line from stdin.

def readShort(): Short

Reads a Short value from an entire line from stdin.

def readf(format: String): List[Any]

Reads in structured input from stdin as specified by the format specifier.

def readf1(format: String): Any

Reads in structured input from stdin as specified by the format specifier, returning only the first value extracted, according to the format specification.

def readf2(format: String): (Any, Any)

Reads in structured input from stdin as specified by the format specifier, returning only the first two values extracted, according to the format specification.

def readf3(format: String): (Any, Any, Any)

Reads in structured input from stdin as specified by the format specifier, returning only the first three values extracted, according to the format specification.

Similarly if you want to read multiple user inputs from the same line ex: name, age, weight you can use the Scanner object

import java.util.Scanner

// simulated input
val input = "Joe 33 200.0"
val line = new Scanner(input)
val name = line.next
val age = line.nextInt
val weight = line.nextDouble

abridged from Scala Cookbook: Recipes for Object-Oriented and Functional Programming by Alvin Alexander

Comments

23

From the Scala maling list (formatting and links were updated):

Short answer:

readInt

Long answer:

If you want to read from the terminal, check out Console.scala. You can use these functions like so:

Console.readInt

Also, for your convenience, Predef.scala automatically defines some shortcuts to functions in Console. Since stuff in Predef is always and everywhere imported automatically, you can use them like so:

readInt

4 Comments

I think it's OK to ask on SO even if it exists elsewhere... The mailing list format is not the easiest one to read.
@huynhjl Indeed, one of the reasons Stack Overflow was created is because it sucks to search mailing lists.
@huynhjl, I agree. Some of us (me) got to this answer via google.
It was asked for a String, not an Int, but of course the answer leads into the right direction. :)
11
object InputTest extends App{

    println("Type something : ")
    val input = scala.io.StdIn.readLine()
    println("Did you type this ? " + input)

}

This way you can ask input.

scala.io.StdIn.readLine()

Comments

8

You can take a user String input using readLine().

import scala.io.StdIn._

object q1 {
  def main(args:Array[String]):Unit={  
    println("Enter your name : ")
    val a = readLine()
    println("My name is : "+a)
  }
}

Or you can use the scanner class to take user input.

import java.util.Scanner;

object q1 {
  def main(args:Array[String]):Unit={ 
      val scanner = new Scanner(System.in)
    println("Enter your name : ")
    val a = scanner.nextLine()
    println("My name is : "+a)
  }
}

1 Comment

"Cannot resolve symbol readLine" Am I missing an import of some sort?
1

Simple Example for Reading Input from User

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

scala> println("What is your name") What is your name

scala> val name = scanner.nextLine()
name: String = VIRAJ

scala> println(s"My Name is $name")
My Name is VIRAJ

Also we can use Read Line

val name = readLine("What is your name ")
What is your name name: String = Viraj

Comments

1

In Scala 2:

import java.io._
object Test {
    // Read user input, output
    def main(args: Array[String]) {

        // create a file writer
        var writer = new PrintWriter(new File("output.txt"))

       // read an int from standard input
       print("Enter the number of lines to read in: ")
       val x: Int = scala.io.StdIn.readLine.toInt

       // read in x number of lines from standard input
       var i=0
       while (i < x) {
           var str: String = scala.io.StdIn.readLine
           writer.write(str + "\n")
           i = i + 1
       }

       // close the writer
       writer.close
     }
}

This code gets input from user and outputs it:

[input] Enter the number of lines to read in: 2
one
two

[output] output.txt
one
two

Comments

0
Using a thread to poll the input-readLine:

// keystop1.sc

// In Scala- or SBT console/Quick-REPL: :load keystop1.sc
// As Script: scala -savecompiled keystop1.sc

@volatile var isRunning = true
@volatile var isPause = false

val tInput: Thread = new Thread {
  override def run: Unit = {
    var status = ""
        while (isRunning) {
            this.synchronized {
                status = scala.io.StdIn.readLine()
                status match {
                    case "s" => isRunning = false
                    case "p" => isPause = true
                    case "r" => isRunning = true;isPause = false
                    case _ => isRunning = false;isPause = false
                }
                println(s"New status is: $status")
            }
        }
    }
}

tInput.start

var count = 0
var pauseCount = 0

while (isRunning && count < 10){
  println(s"still running long lasting job! $count")
  if (count % 3 == 0) println("(Please press [each + ENTER]: s to stop, p to pause, r to run again!)")
  count += 1
  Thread sleep(2000) // simulating heavy computation
  while (isPause){
      println(s"Taking a break ... $pauseCount")
      Thread sleep(1000)
      pauseCount += 1
      if (pauseCount >= 10){
        isPause = false
        pauseCount = 0
        println(s"Taking a break ... timeout occurred!")
      }
  }
}
isRunning = false
println(s"Computation stopped, please press Enter!")
tInput.join()
println(s"Ok, thank you, good bye!")

Comments

0

readLine() lets you prompt the user and read their input as a String

val name = readLine("What's your name? ")

Comments

-5

please try

scala> readint

please try this method

1 Comment

Consider adding some explanation.

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.