Read multiline data from console in Kotlin
This post will discuss how to read multiline data from the console in Kotlin.
1. Using Scanner
We can use two scanners, where the first scanner fetches each line with the Scanner.nextLine() function, and the second scanner scan through it using Scanner.next().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Scanner fun main() { val scanner = Scanner(System.`in`) while (scanner.hasNextLine()) { val tokens = mutableListOf<String>() val lineScanner = Scanner(scanner.nextLine()) while (lineScanner.hasNext()) { tokens.add(lineScanner.next()) } lineScanner.close() println(tokens) } scanner.close() } |
The above solution can be optimized to only use a single scanner. The idea is to read tokens from each line using the split() function from the String class.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.Scanner fun main() { val scanner = Scanner(System.`in`) while (scanner.hasNextLine()) { val tokens = scanner.nextLine().split("\\s".toRegex()).toTypedArray() println(tokens.contentToString()) } scanner.close() } |
Here’s equivalent code using only Scanner.next():
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.* fun main() { val tokens = mutableListOf<String>() val scanner = Scanner(System.`in`) while (scanner.hasNext()) { tokens.add(scanner.next()) } scanner.close() println(tokens) } |
2. Using BufferedReader
Another option to read multiline input from the console in Kotlin is using the BufferedReader class, which is synchronized. The following example demonstrates this by reading each line with the readLine() function and then using the split() function to split it into the individual tokens (using whitespace as a separator).
|
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() { val br = BufferedReader(InputStreamReader(System.`in`)) var line: String try { while (br.readLine().also { line = it } != null) { val tokens = line.split("\\s".toRegex()).toTypedArray() println(tokens.contentToString()) } br.close() } catch (e: IOException) { e.printStackTrace() } } |
To close all resources properly, consider using the use block:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.io.BufferedReader import java.io.InputStreamReader fun main() { try { InputStreamReader(System.`in`).use { inp -> BufferedReader(inp).use { buffer -> var line: String while (buffer.readLine().also { line = it } != null) { val tokens = line.split("\\s".toRegex()).toTypedArray() println(tokens.contentToString()) } } } } catch (e: Exception) { e.printStackTrace() } } |
That’s all about reading multiline data 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 :)