简体   繁体   中英

How can I read an int to use in a for loop?

How can I read an integer value from the user to use in the range of a for loop?

fun main() {
    var n = readLine()
    for (i in 1..n) {
      var (a, b) = readLine()!!.split(' ')
      println(a.toInt() + b.toInt())
    }
}

You can use the String.toInt() function to achieve this (the same thing that you doing in later lines).

Like this:

fun main() {
    val n = readLine()!!.toInt()
    for (i in 1..n) {
      val (a, b) = readLine()!!.split(' ')
      println(a.toInt() + b.toInt())
    }
}

Also, you can replace your var s with val s since they are not changed anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM