Read Integer and Floating-Point Numbers from the Console in Scala
Scala provides the scala.io.StdIn object for reading values entered through standard input. For numeric console input, you can use methods such as readInt(), readLong(), readFloat(), and readDouble().
The following table shows the commonly used methods and the Scala value type returned by each one.
| Method | Returned type | Example input |
|---|---|---|
StdIn.readInt() | Int | 42 |
StdIn.readLong() | Long | 9000000000 |
StdIn.readFloat() | Float | 25.64 |
StdIn.readDouble() | Double | 3.14159 |
You can call these methods with their fully qualified names, such as scala.io.StdIn.readInt(), or import scala.io.StdIn and use the shorter form StdIn.readInt().
Read an Integer from the Scala Console
In this example, we shall read an Integer from console. We will increment the value and print it to the console.
example.scala
object ReadInputExample {
def main(args: Array[String]) {
print("Enter a number: ")
var hours = scala.io.StdIn.readInt()
hours = hours + 1
println("Your entry + 1 : "+hours)
}
}
Output
Enter a number: 256
Your entry + 1 : 257
The readInt() method reads the complete input line and converts it to an Int. In this example, the entered value is stored in hours, increased by one, and then printed.
readInt() accepts input that can be parsed as a valid 32-bit signed integer. Entering text, a decimal value such as 12.5, or a number outside the Int range causes a NumberFormatException.
Read a Float from the Scala Console
In this example, we shall read a float value from console. We will increment the value and print it to the console.
example.scala
object ReadInputExample {
def main(args: Array[String]) {
print("Enter a float value : ")
var length = scala.io.StdIn.readFloat()
length = length + 1
println("Your entry + 1 : "+length)
}
}
Output
Enter a float value : 25.64
Your entry + 1 : 26.64
The readFloat() method converts the entered text to a Float. It accepts decimal input such as 25.64 and whole-number input such as 25. The returned value still has the Scala type Float.
Read a Double for Higher-Precision Decimal Input
Use readDouble() when a program needs a Double rather than a Float. A Double generally preserves more decimal precision and is the usual choice for decimal calculations in Scala unless a Float is specifically required.
import scala.io.StdIn
object ReadDoubleExample {
def main(args: Array[String]): Unit = {
print("Enter the radius: ")
val radius = StdIn.readDouble()
val area = math.Pi * radius * radius
println(s"Area: $area")
}
}
Sample output
Enter the radius: 2.5
Area: 19.634954084936208
Read a Long Integer from Standard Input
An Int cannot hold values outside the 32-bit signed integer range. Use readLong() when the entered whole number may be larger.
import scala.io.StdIn
object ReadLongExample {
def main(args: Array[String]): Unit = {
print("Enter a large whole number: ")
val value: Long = StdIn.readLong()
println(s"You entered: $value")
}
}
Enter a large whole number: 9000000000
You entered: 9000000000
Handle Invalid Numeric Input without Terminating the Program
The direct numeric methods throw a NumberFormatException when the user enters an invalid value. For user-facing programs, it is often safer to read the input as text with readLine() and then attempt the conversion.
The following example uses scala.util.Try to check whether the input can be converted to an integer.
import scala.io.StdIn
import scala.util.Try
object SafeIntegerInput {
def main(args: Array[String]): Unit = {
print("Enter an integer: ")
val input = StdIn.readLine().trim
Try(input.toInt).toOption match {
case Some(number) => println(s"You entered $number")
case None => println("The entered value is not a valid integer.")
}
}
}
Output for invalid input
Enter an integer: twelve
The entered value is not a valid integer.
Keep Asking Until the User Enters a Valid Integer
A console application can repeat the prompt instead of ending after invalid input. The function below continues reading lines until toIntOption returns a value.
import scala.io.StdIn
object RepeatedIntegerInput {
def readInteger(): Int = {
var number: Option[Int] = None
while (number.isEmpty) {
print("Enter an integer: ")
number = StdIn.readLine().trim.toIntOption
if (number.isEmpty) {
println("Invalid input. Enter a whole number.")
}
}
number.get
}
def main(args: Array[String]): Unit = {
val value = readInteger()
println(s"Accepted value: $value")
}
}
String.toIntOption is available in Scala 2.13 and Scala 3. For older Scala versions, use Try(input.toInt).toOption as shown in the previous example.
Read Multiple Numbers Entered on One Console Line
Methods such as readInt() are convenient when each prompt expects one value. To read several numbers from one line, read the line as a string, split it on whitespace, and convert each token.
import scala.io.StdIn
object ReadMultipleNumbers {
def main(args: Array[String]): Unit = {
print("Enter two integers separated by a space: ")
val numbers = StdIn.readLine()
.trim
.split("\\s+")
.map(_.toInt)
val first = numbers(0)
val second = numbers(1)
println(s"Sum: ${first + second}")
}
}
Enter two integers separated by a space: 12 8
Sum: 20
Production code should also verify that the expected number of tokens was entered and that every token is numeric before accessing array elements.
StdIn Numeric Methods versus readLine Conversion
| Approach | Suitable use | Invalid-input behavior |
|---|---|---|
StdIn.readInt(), readFloat(), and similar methods | Small examples and trusted input | Throws an exception |
StdIn.readLine().toInt | When the original text may also be needed | Throws an exception |
StdIn.readLine().toIntOption | Input validation in Scala 2.13 or Scala 3 | Returns None |
Try(StdIn.readLine().toInt) | Validation compatible with older Scala versions | Returns a failed Try |
Common Errors When Reading Numbers in Scala
- Entering a decimal for
readInt(): An input such as10.5is not an integer and causes a parsing error. - Using
Intfor very large values: UseLongandreadLong()when the value may exceed theIntrange. - Assuming every input is valid: Interactive applications should validate text before converting it.
- Using
Floatwhen more precision is needed: PreferDoublefor general decimal calculations. - Reading several values with one numeric method call: Use
readLine(),split(), and conversion when multiple numbers appear on the same line.
Frequently Asked Questions about Scala Console Number Input
How do you read an integer from the console in Scala?
Call scala.io.StdIn.readInt(). You can also import scala.io.StdIn and call StdIn.readInt(). The method returns an Int.
How do you read a decimal number in Scala?
Use StdIn.readDouble() for a Double or StdIn.readFloat() for a Float. Double is usually preferable when additional decimal precision is useful.
What happens when readInt receives non-numeric input?
readInt() attempts to parse the entered line as an integer. Invalid input causes a NumberFormatException. Read the value with readLine() and use toIntOption or Try when invalid input must be handled safely.
How can Scala read two integers from the same line?
Read the complete line with StdIn.readLine(), split it using a whitespace expression such as split("\\s+"), and convert the resulting strings to integers.
Is java.util.Scanner required for Scala console input?
No. Scala programs can use scala.io.StdIn directly for common console-input tasks. Java’s Scanner remains available through Java interoperability, but it is not required for reading an integer, float, double, or line in Scala.
Scala Console Number Input Editorial Checklist
- Confirm that each input method matches the declared Scala numeric type.
- Check that integer examples do not include decimal input.
- Use
Longfor examples that exceed theIntrange. - Show invalid-input handling when the example is intended for interactive use.
- Verify whether
toIntOptionis supported by the Scala version used in the tutorial. - Mark program output separately from executable Scala code.
TutorialKart.com