Kotlin 中的多变量 For 循环 [英] For Loop with Multivariable in Kotlin
本文介绍了Kotlin 中的多变量 For 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 kotlin 中仅使用一个 for 循环来执行此 java 代码?
How can I do this java code in kotlin using just one for loop?
for(int i=0, j=0; i < 6 && j < 6; i++, j+=2) {
// code here
}
推荐答案
非常感谢 gidds 的回答
I really appreciate gidds's answer
但是还有另一种更简单的方法来为两个变量
but there is another easier way to write for in loops for two variables
for ( (i, j) in (0..6).zip(0..6 step 2)){
println("values are: $i, $j")
}
以上代码运行正常
您还可以为三个变量轻松编写for in循环.看下面的代码.
you can also write for in loops easily for three variable. See the following code.
在这段代码中,我试图实现一个三变量系列
In this code I tried to implement a three variable series
// 1.2.3 + 2.3.4 + 3.4.5 + ... + n(n+1)(n+2)
fun main(args: Array<String>) {
// taking int input from console
val number: Int = readLine()!!.toInt()
var sum: Int = 0
// here second variable jPair becomes pair because of second nested zip
for ( (i, jPair) in (1..number).zip((0..number + 1).zip(2..number + 2))) {
println("values are: $i, ${jPair.first}, ${jPair.second}")
sum += (i * jPair.first * jPair.second)
}
println("Series sum is: $sum")
}
现在,让我们实现四个变量 for in 循环
在下面的代码中,我试图实现一个四变量系列
In the following code I am trying to implement a four variable series
// 1.3.5.7 + 3.5.7.9 + 5.7.9.11 + ... + n(n+2)(n+4)(n+6)
fun main(args: Array<String>) {
// taking int input from console
val number: Int = readLine()!!.toInt()
var sum: Int = 0
// here second variable iPair becomes pair because of first nested zip
// here second variable jPair becomes pair because of second nested zip
for ( (iPair, jPair) in ((1..number step 2).zip(3..number + 2 step 2)).zip((5..number + 4 step 2).zip(7..number + 6 step 2))) {
println("values are: ${iPair.first}, ${iPair.second}, ${jPair.first}, ${jPair.second}")
sum += (iPair.first * iPair.second * jPair.first * jPair.second)
}
println("Series sum is: $sum")
}
通过这种方式,我们可以轻松实现多个变量 for in 循环.
This way we can implement multiple variable for in loops easily.
这篇关于Kotlin 中的多变量 For 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文