Kotlin Program to Read and Print Integer

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

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.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners