4 ways to print an integer entered by the user in Kotlin

Kotlin program to print an integer entered by the user:

In this post, we will learn how to take an integer as input from the user and print it on the console. To read any user input value, we use the Scanner class. We can create an object of the Scanner class and use it to read the value. Kotlin also provides another method called readLine to read a user-input value. I will show you both ways to read an integer in this post.

Method 1: Kotlin program to read a user-input integer by using Scanner and print it:

Let’s try it with the Scanner class. Let’s take a look at the below program:

import java.util.Scanner

fun main() {
    val scanner = Scanner(System.`in`)

    print("Enter a number: ")
    val number = scanner.nextInt()

    println("Entered number: $number")
}

Here,

  • scanner is a Scanner object. We have to import it from java.util.Scanner. This is the same Scanner class we use in Java programs.
  • It asks the user to enter a number.
  • The nextInt method of the Scanner class reads the next token of the input as an integer. It returns the integer and it is assigned to the variable number.
  • The last line is printing the number variable, i.e. the number entered by the user.

If you run this program, it will print output as like below:

Enter a number: 12
Entered number: 12

Enter a number: 2234
Entered number: 2234

Method 2: Read an integer entered by the user in Kotlin by using readLine() method:

The readLine method reads a line of input from the standard input stream. It returns the line read or null. The below program uses readLine() to read the input from the user and it prints that value:

fun main() {
    print("Enter a number: ")
    val number = readLine()?.toInt()

    println("Entered number: $number")
}

It will print output similar to the above example.

Enter a number: 435
Entered number: 435

Method 3: Use readln() method to read an integer entered by the user in Kotlin:

There is another method called readln() to read a line of input from the standard input stream. It will read the line of input and return it or it will throw RuntimeException for null values.

fun main() {
    print("Enter a number: ")
    val number = readln().toInt()

    println("Entered number: $number")
}

We have to convert the value to integer with the toInt method. It will print similar output.

Kotlin example to print an integer in different ways

Method 4: By using readlnOrNull method:

The readln() method calls readLnOrNull method. This method is also available to use. It reads the user input and returns it. For empty value, or if EOF is already reached, it returns null.

fun main() {
    print("Enter a number: ")
    val number = readlnOrNull()?.toInt()

    println("Entered number: $number")
}

This method will print similar results.

Enter a number: 556
Entered number: 556

You might also like: