Niklas Flink
Niklas Flink

Reputation: 101

readLine for a variable number of Ints

Is there a way to code something like this in kotlin for a variable number of ints? For example the input should be "1 3 5" or "3 2 2 7" (String with space-separated Ints). And I am not allowed to use java librarys.

val (x, y) = readLine()!!.split(' ').map(String::toInt)
println(x+y)

Thanks in advance.

Upvotes: 2

Views: 811

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40078

If you want to just print each string, then you can use forEach

readLine()!!.split(' ').forEach{ println(it) }

If you want to print as int, then you can use forEach with toInt()

readLine()!!.split(' ').forEach{ println(it.toInt()) }

Or if you want sum you can use sumBy directly

readLine()!!.split(' ').sumBy{ it.toInt() }

Upvotes: 2

Niklas Flink
Niklas Flink

Reputation: 101

Found a solution for my problem:

var list: List<Int> = readLine()!!.split(' ').map(String::toInt)
for(m in  list){
    println(m)
}

Upvotes: 0

Related Questions