Read Number from Console Input – Scala
If you are developing a console application with Scala, you may need to read input from the user.
In this tutorial, we will learn how to read a number from the console as input from a user.
To read a number from console input, we use the method scala.io.StdIn.readInt()
, scala.io.StdIn.readFloat()
.
Example 1 – Read Integer from Console as Input
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
readInt()
method accepts only integers as input. If you provide a float or string, java.lang.NumberFormatException
occurs and the program exits abruptly with exit code 1.
Example 2 – Read Float from Console as Input
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
Using readFloat(), when the console prompts for the input, you provide float, or int or any value of datatype that can be auto typecasted to float.