【问题标题】:How can I read an int to use in a for loop?如何读取 int 以在 for 循环中使用?
【发布时间】:2021-10-03 10:40:40
【问题描述】:

如何从用户那里读取整数值以在for 循环的范围内使用?

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

【问题讨论】:

标签: kotlin for-loop generics


【解决方案1】:

您可以使用 String.toInt() 函数来实现这一点(与您在后面几行中所做的相同)。

像这样:

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

此外,您可以将 vars 替换为 vals,因为它们在任何地方都没有更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多