Braian Coronel
Braian Coronel

Reputation: 22905

How to implement readLine()!!.toIntArray() on Kotlin?

I would like to implement a function or some way to store an array sequentially from a console. Something like this: readLine()!!.toIntArray()

Would it be convenient to use a loop for this or could it be avoided?

And then you can access them using the index of the array.

fun main(args: Array<String>) {
    myFunction()
}

A:

fun myFunction() {
    println(" . First number: ")
    val num1:Float = readLine()!!.toFloat()
    println(" . Second number: ")
    val num2:Float = readLine()!!.toFloat()
    println(" . Third number: ")
    val num3:Float = readLine()!!.toFloat()
    println(" . Fourth number: ")
    val num4:Float = readLine()!!.toFloat()

    val result:Float = (num1+num2) + (num3*num4)
    print("The result is: $result")
}

B:

fun myFunction() {
    println("Enter four numbers ...")
//    val numbers:IntArray = intArrayOf(45, 22, 10, 13)
    val numbers:IntArray = readLine()!!.toIntArray()   //HERE: toIntArray() isn't defined

    val result:Int = (numbers[0]+numbers[1]) + (numbers[2]*numbers[3])
    print("The result is: $result")
}

When defining the Array I will have to indicate the amount of values that I want to be read from the console, that is, the size of the Array.

Or is there another way to stop reading data in the console?

In short, I want to move from block A to the idea of block B.

SOLUTION

println("Enter four numbers ...")
val numbers = readLine()!!.split(" ").map { it.toInt() }

val result:Int = (numbers[0]+numbers[1]) + (numbers[2]*numbers[3])
print("The result is: $result")

Upvotes: 2

Views: 4263

Answers (2)

voddan
voddan

Reputation: 33829

If you need to read the numbers from separate lines like in your examples:

val list = List(4) { readline()!!.toFloat() }

The same can be done with arrays, but it is recommended to use lists in Kotlin

Upvotes: 1

H&#233;ctor
H&#233;ctor

Reputation: 26084

You don't need a loop. It can be done with map:

val numbers = readLine()!!.split(" ").map { it.toInt() }

Upvotes: 3

Related Questions