Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-loop with multiple variable declarations

Tags:

java

groovy

I'm pretty sure the following is legal in Java

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

But when I try to run it in the Groovy console, I get this error

unexpected token: =

Are multiple variable declarations unsupported by Groovy or is there another reason why this isn't allowed?

like image 321
Dónal Avatar asked Dec 09 '14 18:12

Dónal


People also ask

Can you declare more than one variable in for of?

Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.

Can you have two arguments in a for-loop?

With two arguments in the range function, the sequence starts at the first value and ends one before the second argument. Programmers use x or i as a stepper variable.

Can you declare a variable in a for-loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Can I use multiple variables in for-loop Python?

Can you have 2 variables in a for loop Python? By using zip() and enumerate(), we can iterate with two variables in a for loop. We can also iterate with two elements in a dictionary directly using for loop.


1 Answers

It's a common gotcha for Java Developers. See this link for more detail:

Common gotchas you can use only one count variable.

Excerpts from the 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 {
   ...
}
like image 194
Uncle Iroh Avatar answered Oct 09 '22 08:10

Uncle Iroh