gpt4 book ai didi

java - 具有多个变量声明的 for 循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:09:22 31 4
gpt4 key购买 nike

我很确定以下内容在 Java 中是合法的

for (int var1 = 2, var2 = 3; var1 < 10; ++var1) {
System.out.println(var1);
}

但是当我尝试在 Groovy 控制台中运行它时,我得到了这个错误

unexpected token: =

Groovy 是否不支持多个变量声明,或者是否有其他原因不允许这样做?

最佳答案

这是 Java 开发人员的常见问题。看这个link更多详情:

常见陷阱您只能使用一个计数变量

链接摘录:

for Loops

Another small difference is that you can’t initialize more than one variable in the first part of a for loop, so this is invalid:

for (int count = someCalculation(), i = 0; i < count; i++) {
...
}

and you’ll need to initialize the count variable outside the loop (a rare case where Groovy is more verbose than Java!):

int count = someCalculation()
for (int i = 0; i < count; i++) {
...
}

or you could just skip the whole for loop and use times:

someCalculation().times {
...
}

关于java - 具有多个变量声明的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27386138/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com