多重初始化在 “for” 循环中不会编译。

huangapple go评论62阅读模式
英文:

Groovy. Multiple initialization in "for" loop doesn't compile

问题

以下是您提供的代码的中文翻译部分:

在使用IntelliJ IDEA中内置的Groovy工具执行以下代码时,出现了错误。

StringBuilder sb = new StringBuilder()

String a = "abc"

String b = "123"

for (int i = 0, j = 0; i < a.length() || j < b.length(); i++, j++) {
    if (i < a.size()) {
        print(a[i])
        sb.append(a[i])
    }
}

print(sb)

错误信息如下:

org.codehaus.groovy.control.MultipleCompilationErrorsException: 启动失败:
ideaGroovyConsole.groovy: 8: 意外的标记:= @ 行 8, 列 12。
   for (int i = 0, j = 0; i < a.length() || j < b.length(); i++, j++) {
              ^

1 个错误

	at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
	at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:150)
	at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:120)
for (int i = 0, j = 0; i < a.length() || j < b.length(); i++, j++) {

我的猜测是语法问题,但没有提出任何问题。

英文:

When I executed the following code using the built-in Groovy tool in IntelliJ IDEA, an error occurred.

StringBuilder sb = new StringBuilder()

String a = &quot;abc&quot;

String b = &quot;123&quot;


for (int i = 0, j = 0; i &lt; a.length() || j &lt; b.length(); i++, j++) {


    if (i &lt; a.size()) {
        print(a[i])

        sb.append(a[i])
    }

}

print(sb)

Error is as follows

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
ideaGroovyConsole.groovy: 8: unexpected token: = @ line 8, column 12.
   for (int i = 0, j = 0; i &lt; a.length() || j &lt; b.length(); i++, j++) {
              ^

1 error

	at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
	at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:150)
	at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:120)
for (int i = 0, j = 0; i &lt; a.length() || j &lt; b.length(); i++, j++) {

My guess is that the grammar problems, but didn't send any questions。

答案1

得分: 0

我使用的 Groovy 版本是多少?在某个时候,Groovy 不支持在 for 循环的第一部分初始化多个变量。查看更多信息:https://stackoverflow.com/a/27386418/1842599

我已经检查过 Groovy 4(我安装了 4.0.8),多个初始化工作得非常好。

因此,如果升级不可行,您可以考虑升级您的 Groovy 版本或重新编写您的代码。

英文:

What version of Groovy do you use? At some point Groovy didn't support initialization of more than one variable in the first part of a for loop. See more: https://stackoverflow.com/a/27386418/1842599

I've checked with Groovy 4 (I have 4.0.8 installed), multiple initialization works like a charm.

So, you may consider upgrading your Groovy version or rewrite your code, if upgrade is not possible.

huangapple
  • 本文由 发表于 2023年6月27日 18:50:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定