- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Kotlin Program to Read The Number From Standard Input
In this article, we will understand how to read a number from standard input in Kotlin. The ‘nextInt’ method is used to read the number.
Below is a demonstration of the same
Suppose our input is
45
The desired output would be
The input value is 45
Algorithm
Step 1 − Start
Step 2 − Declare an integer: value
Step 3 − Define the integer
Step 4 − Read the values
Step 5 − Display the value
Step 6 − Stop
Example 1
In this example, we will read the number from the standard input using the Scanner(). First, we imported the java.util.Scanner to use the Scanner() for input −
import java.util.Scanner
Then, a scanner object is created in the main() function −
val input_scanner = Scanner(System.`in`)
The user enters the input using the System.`in`. After that, the nextLine() method reads the string value from the user −
var input_string:String = input_scanner.nextLine()
Let us now see the complete example −
import java.util.Scanner fun main(args: Array<String>) { System.out.println("The required packages have been imported
"); val input_scanner = Scanner(System.`in`) print("Enter an integer: ") var input_integer:Int = input_scanner.nextInt() println("The value is: $input_integer") }
Output
The required packages have been imported Enter an integer:45 The value is:5
Example 2
Here, we will create a custom function to read the number from the standard input using the Scanner −
import java.util.Scanner fun scan_value(){ val input_scanner = Scanner(System.`in`) print("Enter an integer: ") var input_integer:Int = input_scanner.nextInt() println("The value is: $input_integer") } fun main(args: Array<String>) { System.out.println("The required packages have been imported
"); scan_value() }
Output
The required packages have been imported Enter an integer:45 The value is: 45