Scala - Input and Output



You can take input from the user and can also display it as output in Scala. This is useful when you work with loops, conditional statements and other Scala constructs. Here, we have discussed command-line input and output with Scala.

Writing Output

You can display output in various ways, you can output to standard out (STDOUT).

Print with newline

You can use `println` command to print statements and with newline.

println("This is statement and there will be a newline after it")

For example,

object PrintExample {
   def main(args: Array[String]) {
      println("This is a statement, and there will be a newline after it")
      println("You can print multiple lines with different statements.")
   }
}

Print without newline

You can use `print` command to print statements and without newline.

print("This is statement but there will not be any newline after it, till you do")

For example,

object PrintExample {
   def main(args: Array[String]) {
      print("This is a statement, but there will not be any newline after it,")
      print("till you do.")
   }
}

Print to standard error (STDERR)

System.err.printlin("This error has occurred")

For example,

object ErrorExample {
   def main(args: Array[String]) {
      System.err.println("This error has occurred")
      System.err.println("Another error message.")
   }
}

In these examples, first two use `println` and `print` function on standard output (STDOUT) and last one `System.err.println` function on standard error (STDERR). Note that when we use commands like, println, String, Int, Float etc, you need not to import them explicitly.

Reading Input

You can read input from the console and from other sources using various methods and libraries.

Reading from the Console

You can use `scala.io.StdIn` for console input. You can read a line of text from the console.

val input = scala.io.StdIn.readLine("Enter something: ")
println(s"You entered: $input")

The command `readLine` is the easiest way which belongs in `scala.io.package`. So you need to import it before use. Like,

import scala.io.StdIn.readLine

Then you use it, for example,

import scala.io.StdIn.readLine

object TemperatureConversion extends App {
   print("Enter temperature in Celsius: ")
   val celsius = readLine().toDouble

   val fahrenheit = (celsius * 9/5) + 32
   println(s"$celsiusC is equal to $fahrenheitF")
}

Then you can compile it using `scalac`,

$ scalac TemperatureConversion.scala

Then execute it

$ scala TemperatureConversion 

You will need to provide required input here.

You can also use `scala.io.StdIn.readInt()` and `scala.io.StdIn.readDouble()` etc to read specific data types input from the console.

Reading from Files

You can use `scala.io.Source` for file input.

import scala.io.Source

val source = Source.fromFile("input.txt")
val lines = source.getLines()
for (line <- lines) {
   println(line)
}
source.close()

Reading from other Sources

You can also use `scala.io.StdIn.readLine()` and `scala.io.StdIn.readChar()` to read input from standard input. These are some methods to read input input in Scala.

These are standard way to read integer values in Scala:

Method Description
readBoolean() Reads a Boolean value from an entire line from stdin.
readByte() Reads a Byte value from an entire line from stdin.
readChar() Reads a Char value from an entire line from stdin.
readDouble() Reads a Double value from an entire line from stdin.
readFloat() Reads a Float value from an entire line from stdin.
readInt() Reads an Int value from an entire line from stdin.
readLine(text: String, args: Any*) Prints formatted text to stdout and reads a full line from stdin.
readLine() Reads a full line from stdin.
readLong() Reads a Long value from an entire line from stdin.
readShort() Reads a Short value from an entire line from stdin.
readf(format: String) Reads in structured input from stdin as specified by the format specifier.
readf1(format: String) Reads in structured input from stdin as specified by the format specifier, returning only the first value extracted, according to the format specification.
readf2(format: String) Reads in structured input from stdin as specified by the format specifier, returning only the first two values extracted, according to the format specification.
readf3(format: String) Reads in structured input from stdin as specified by the format specifier, returning only the first three values extracted, according to the format specification.

Note

You can take user String input in Scala using `readLine()` and `Scanner` class.

For example, using `readLine()`

import scala.io.StdIn._

object ReadLineExample {
   def main(args: Array[String]): Unit = {
      println("Enter your favorite color: ")
      val color = readLine()
      println("Your favorite color is: " + color)
   }
}

Using `Scanner`

import java.util.Scanner

object ScannerExample {
   def main(args: Array[String]): Unit = {
      val scanner = new Scanner(System.in)
      println("Enter your favorite food: ")
      val food = scanner.nextLine()
      println("Your favorite food is: " + food)
   }
}

If you want to read many inputs from the same line, then you need to use `Scanner` object for it.

import java.util.Scanner
Advertisements