Reading console input in Kotlin

Recently i just begin to improve my algorithm using Kotlin. I tried to solve some problem and then with some input how can i code the output from that problem.

Some input need to read and become my variable in my code. So how can i read input from console?
I have some best practice to read inputs from console in Kotlin. The solution is using Scanner and readLine()
I begin with top-level function:

fun main(args: Array<String>) {    // this is your main code}

in example we want to sum A and B from as input:

fun main(vararg args: String) {  val (a, b) = readLine()!!.split(' ')  println(a.toInt() + b.toInt())}


fun main(vararg args: String) {  val (a, b) = readLine()!!.split(' ').map(String::toInt)  println(a + b)}


fun readInts(separator: Char = ' ') = readLine()!!.split(separator).map(String::toInt)fun main(vararg args: String) {  val (a, b) = readInts()  println(a + b)}


import java.util.Scannerfun main(vararg args: String) {  val input = Scanner(System.`in`)  val a = input.nextInt()  val b = input.nextInt()  println(a + b)}


with(Scanner(System.`in`)) {    val a = nextInt()    val b = nextInt()    println(a + b)}

Beware that Scanner is somewhat slow. This may be important in some cases like competitive programming where program’s execution on large inputs could be made up to two times faster just by replacing Scanner with plain readLine.


See also  Accessing StreamingAssets in Android or iOS

About wahyuway

Check Also

Cannot Launch Android Emulator

Android Emulator is useful when you want to debug locally inside your environment. We can …

Leave a Reply