Kotlin Program to Read and Print Integer

In this post, we will go through Kotlin program to read and print integer.

You can read values in 2 ways –

  1. Using Scanner
  2. Without Using Scanner

1. Print Integer – Using Scanner and nextInt()

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter integer:")
    val a = read.nextInt()

    println("Entered integer value = $a")
}

When you run the program, output will be

Enter integer:
76
Entered integer value = 76

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextInt() means read next integer from standard input – Keyboard.
Input read by scanner is then stored in variable a

Finally, we print read value using println() method.

2. Kotlin Program to Print Integer (Without Using Scanner)

fun main() {

    println("Enter integer: ")

    val sInput = readLine()!!

    val a: Int = sInput.toInt()

    println("Entered integer value: $a")

}

When you run the program, output will be

Enter integer:
54
Entered integer value: 54

We have used readLine() method to read values from standard input – Keyboard.
!! operator just makes sure value is not null. So,
readLine()!! returns not null value from standard input – Keyboard.

Value returned by readLine()!! is stored in a variable sInput.
Then, we are converting that value into integer by using toInt() method, then, stored converted integer
value in variable a

Finally, we print variable a using println() method.

Thus, we went through Kotlin program to read and print integer.

Leave a Reply