Read String form Console in Kotlin
To read a string from consoled entered by user in Kotlin, you can use readLine()
function.
readLine()
When the readLine()
function is executed, a prompt appears in the standard console input, and you or any other user can enter an input there. After you enter a string in the console, press enter key. The entered input is returned as a string by the readLine()
function.
We can store the value returned by the readLine()
function in a variable, and use the value in the program.
val input = readLine()
Examples
1. Read the name of user from console
In the following program, we take an Array of strings in arr
, and fetch the last element from the Array.
Kotlin Program
fun main(args: Array<String>) {
val firstname = readLine()
println("Hello $firstname")
}
Output
Prompt the user for input
When you do not prompt anything to the console, it may create a confusion of what to enter in the console. So, it is always good to prompt user for the action to be done.
For example, in our previous program we read the firstname of the user. For the prompt, let us give the message "Enter your Firstname : "
.
Kotlin Program
fun main(args: Array<String>) {
print("Enter your Firstname : ")
val firstname = readLine()
println("Hello $firstname")
}
Output
Please note that we have used print() function to display the prompt, so that when user enters an input, it appears right after the prompt message.