Read input from console in Kotlin
This post will discuss how to read input from the console in Kotlin.
1. Using Scanner
A simple solution is to use the Scanner class for reading input from the console. It splits the input into tokens using whitespace as a separator, which then can be converted into different data types with the corresponding .next*() functions:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Scanner fun main() { val scanner = Scanner(System.`in`) println(scanner.nextLine()) // read the whole line println(scanner.nextInt()) // get the next integer token println(scanner.next()) // get the next string token println(scanner.nextDouble()) // get the next double token println(scanner.nextLong()) // get the next long token scanner.close() // finally, close the scanner } |
2. Using BufferedReader
We can achieve better performance using the BufferedReader class. The idea is to read the whole line as a string using the readLine() function, and convert it into different data types using the standard conversion functions provided by the String class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader fun main() { try { val br = BufferedReader(InputStreamReader(System.`in`)) println(br.readLine()) // read the whole line println(br.readLine().toDouble()) // get double println(br.readLine().toLong()) // get long br.close() // finally, close the stream } catch (e: IOException) { e.printStackTrace() } } |
If the input is an integer, we can directly call the read() function, as shown below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader fun main() { try { val br = BufferedReader(InputStreamReader(System.`in`)) println(br.read()) // get integer br.close() // close the stream } catch (e: IOException) { e.printStackTrace() } } |
3. Using Console
Finally, we can get access to the character-based console to read input from it. The System.console() function returns the Console object associated with the current Java virtual machine.
|
1 2 3 4 5 6 7 8 |
fun main() { val console = System.console() if (console != null) { println(console.readLine()) // read the whole line println(console.readLine().toDouble()) // get double println(console.readLine().toInt()) // get integer } } |
That’s all about reading input from the console in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)