Scala User Input
User input is text that a person types while a program runs. A program asks a question, reads the typed line, and then uses that text in its work.
readLine reads a typed name
The program prints a prompt, then reads one line. The user types Maya, and the program greets that name.
@main def main(): Unit =
print("Enter your name: ")
val name = scala.io.StdIn.readLine()
println(s"Hello, $name!")toInt turns input into a number
The user types 7, which arrives as text. The toInt call turns it into a number that can be doubled.
@main def main(): Unit =
print("Enter a number: ")
val text = scala.io.StdIn.readLine()
val number = text.toInt
println(number * 2)A number from input can grow
The user types the age 20. The program adds one to give the age next year.
@main def main(): Unit =
print("Enter your age: ")
val age = scala.io.StdIn.readLine().toInt
println(s"Next year you will be ${age + 1}")Example
@main def main(): Unit =
print("Name: ")
val name = scala.io.StdIn.readLine()
print("Number: ")
val number = scala.io.StdIn.readLine().toInt
println(s"$name, $number doubled is ${number * 2}")Key points
- readLine: scala.io.StdIn.readLine() reads one line of typed text and gives it back as a String.
- Prompt: a short message printed before reading, so the user knows what to type.
- print: prints text without moving to a new line, so the prompt stays on the typing line.
- toInt: turns text like "42" into the number 42, so it can be used in sums.
- Input type: readLine always gives a String, even when the user types only digits.
- One call, one line: each readLine call reads the next line the user typed.
In this example, the first readLine reads the name Maya as text. The second readLine reads the text 4 and toInt turns it into a number, so the last line can double it and print 8.
Note
Convert input text with toInt before doing arithmetic with it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What type does scala.io.StdIn.readLine() give back?