How to use Scanner class in Kotlin to read user inputs

Published by admin on

Introduction :

Scanner class is actually a Java class. It is defined in java.util package. If you are from Java background, you must be aware of this class and how to use it. In Kotlin also, we can create one Scanner variable and use it to read user inputs.

In this post, I will show you how to use Scanner class in Kotlin with one simple example.

 

Read user input using Scanner in Kotlin :

Let’s write one program to read the user input string using Scanner :

import java.util.Scanner

fun main() {
    val sc = Scanner(System.`in`)
    println("Enter a line : ")
    
    val userInput = sc.nextLine()
    println(userInput)
}

As you can see here, we are creating one Scanner object and reading the user input line using nextLine method. Scanner provides a lot of different methods to read user input values.

 

Sample Output :

Enter a line : 
Hello World !!
Hello World !!

Kotlin scanner example

All methods are define in Scanner.java class and these are same as we use in a Java program.

Categories: kotlin

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *