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

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

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

问题

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

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

  1. StringBuilder sb = new StringBuilder()
  2. String a = "abc"
  3. String b = "123"
  4. for (int i = 0, j = 0; i < a.length() || j < b.length(); i++, j++) {
  5. if (i < a.size()) {
  6. print(a[i])
  7. sb.append(a[i])
  8. }
  9. }
  10. print(sb)

错误信息如下:

  1. org.codehaus.groovy.control.MultipleCompilationErrorsException: 启动失败:
  2. ideaGroovyConsole.groovy: 8: 意外的标记:= @ 8, 12
  3. for (int i = 0, j = 0; i < a.length() || j < b.length(); i++, j++) {
  4. ^
  5. 1 个错误
  6. at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
  7. at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:150)
  8. at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:120)
  1. 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.

  1. StringBuilder sb = new StringBuilder()
  2. String a = &quot;abc&quot;
  3. String b = &quot;123&quot;
  4. for (int i = 0, j = 0; i &lt; a.length() || j &lt; b.length(); i++, j++) {
  5. if (i &lt; a.size()) {
  6. print(a[i])
  7. sb.append(a[i])
  8. }
  9. }
  10. print(sb)

Error is as follows

  1. org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
  2. ideaGroovyConsole.groovy: 8: unexpected token: = @ line 8, column 12.
  3. for (int i = 0, j = 0; i &lt; a.length() || j &lt; b.length(); i++, j++) {
  4. ^
  5. 1 error
  6. at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
  7. at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:150)
  8. at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:120)
  1. 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:

确定