Kotlin Program to Print an Integer (Entered by the User)

In this program, you’ll learn to print an integer entered by the user. The integer is stored in a variable and printed to the screen using nextInt() and println() functions respectively.

Example 1: How to Print an Integer entered by an user in Kotlin using Scanner

  1. import java.util.Scanner
  2. fun main(args: Array<String>) {
  3. // Creates a reader instance which takes
  4. // input from standard input - keyboard
  5. val reader = Scanner(System.`in`)
  6. print("Enter a number: ")
  7. // nextInt() reads the next integer from the keyboard
  8. var integer:Int = reader.nextInt()
  9. // println() prints the following line to the output screen
  10. println("You entered: $integer")
  11. }

When you run the program, the output will be:

Enter a number: 10
You entered: 10

In this example, an object of Scanner class is created, reader which takes input from the user from keyboard (standard input).

Then, nextInt() function reads the entered integer until it encounters a new line character \n (Enter). The integer is then saved in a variable, integer of type Int.

Finally, println() function prints integer to the standard output: computer screen using string templates.


 


Example 2: How to Print an Integer without using Scanner

fun main(args: Array<String>) {

    print("Enter a number: ")

    // reads line from standard input - keyboard
    // and !! operator ensures the input is not null
    val stringInput = readLine()!!

    // converts the string input to integer
    var integer:Int = stringInput.toInt()

    // println() prints the following line to the output screen
    println("You entered: $integer")
}

When you run the program, the output will be:

Enter a number: 10
You entered: 10

In the above program, we use the function readLine() to read a line of string from the keyboard. Since readLine() can also accept null values, !! operator ensures not-null value of variable stringInput.

Then, the string stored in stringInput is converted to an integer value using the function toInt(), and stored in yet another variable integer.

Finally, integer is printed onto the output screen using println().