In this Kotlin tutorial, you shall learn how to read an integer value from console entered by user, using readLine() function, with example programs.

Kotlin – Read integer from console

To read an integer value input by user via console in Kotlin, we can use readLine() function and String.toInt() method.

When readLine() function is executed, the prompt appears in the console for the user to enter an input. User can input a value and after entering all the input, press enter or return key. The readLine() function returns the entered value as a String.

The syntax to call readLine() function is

readLine()

Please note that the function can also return a null value.

Once we got the string value, we convert it to an integer value using String.toInt() method, as shown in the following. Please note that we have used safe call ?. operator.

readLine()?.toInt()

Example

In the following program, we read an integer number to n from user input. We then print the entered value back to console.

Main.kt

fun main() {
    print("Enter an integer : ")
    val n = readLine()?.toInt()
    println("You entered : $n")
}

Output #1

Enter an integer : 12345
You entered : 12345

Output #2

Enter an integer : asdf
Exception in thread "main" java.lang.NumberFormatException: For input string: "asdf"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at MainKt.main(Main.kt:3)
	at MainKt.main(Main.kt)

When we entered an invalid value for an integer, parsing failed and NumberFormatException is thrown.

ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to read an integer from console input using readLine() function and String.toInt() method.