How do i take inputs from user console in Kotlin

Published October 07, 2021


In this Kotlin tutorial we cover how to take inputs from console and print them. To take user inputs from console we will use readline() method and Scanner class.

Let's write code to take user inputs

 

Using ReadLine method

import java.util.Scanner
fun main() {

    print("Enter text: ")
    var inputtext = readLine()
    print("You entered: $inputtext")
}

 

output:

Enter text: Welcome to Kotlin Console input
You entered: Welcome to Kotlin Console input

 

Output 2:

Enter text: 123 Text number true boolean
You entered: 123 Text number true boolean

 

 

Using Scanner class

To read inputs using scanner we need to import java.util.Scanner package.

Let's write example which will ask user to enter integer,float and boolean values

 

import java.util.Scanner
fun main() {

    // create an object for scanner class
    val integer = Scanner(System.`in`)
    print("Enter an integer: ")
    // nextInt() method is used to take
    // next integer value and store in enteredinteger variable
    var enteredinteger:Int = integer.nextInt()
    println("You entered: $enteredinteger")

    val floatvalues = Scanner(System.`in`)
    print("Enter a float value: ")

    // nextFloat() method is used to take next
    // Float value and store in enteredfloatvalues variable
    var enteredfloatvalues:Float = floatvalues.nextFloat()
    println("You entered: $enteredfloatvalues")

    val booleanValue = Scanner(System.`in`)
    print("Enter a boolean: ")
    // nextBoolean() method is used to take
    // next boolean value and store in enteredBoolean variable
    var enteredBoolean:Boolean = booleanValue.nextBoolean()
    println("You entered: $enteredBoolean")
}

 

 

Output:

Enter an integer: 12
You entered: 12
Enter a float value: 1.2
You entered: 1.2
Enter a boolean: true
You entered: true

Process finished with exit code 0

 

 

Suppose if i enter float value instead of Integer on the first argument it will through InputMismatchException error

Enter an integer: 1.2
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at TestKt.main(test.kt:9)
    at TestKt.main(test.kt)

 

 

Conclusion: In this kotlin example we covered how to read user inputs from the console and alos learned what is InputMismatchException  is exception error


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

13 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions