Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comma seperator for the FOR loop

 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So the comma separator is acceptable to separate expressions in the FOR loop. And they say that expressions and variable declarations cannot be mixed. My question is this. Can only expressions be separated in this init part of the for loop
Example
I know this can be done.
int j = 1, k;
for (j = 3, k = 6; j + k < 20; k += 2)
{
System.out.println("j = " + j);
}
What else can be mixed in the init part of the for loop? Is that it? The way they put the wording in the book, it sounds as if I can either do expression separation or init separation, but it seems I can't.
for (int j = 2, int k = 2; j + k < 20; k += 2)
{
System.out.println("j = " + j);
}

Can anyone clear up what EXACTLY can be done with the comma
Regards,
Dale
------------------
By failing to prepare, you are preparing to fail.
Benjamin Franklin (1706 - 1790)
 
CHRIS MELVIN
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am not sure exactly what you are asking. If the question is whether you can declare and initialise multiple variables within the for loop, then yes it is possible:

for (int j = 2, k = 2; j + k < 20; k += 2)
{
System.out.println("j = " + j);
}

I hope this was what you where asking.
 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess my question is this...
What does this statement exactly refer to
"Expressions and variable declarations cannot be mixed with comma seperation in a for loop."

------------------
By failing to prepare, you are preparing to fail.
Benjamin Franklin (1706 - 1790)
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have EITHER a list of statements like your first example, OR a list of declarations. You just already had an "int" declaration there and were repeating yourself when you wrote it again and the compiler didn't like it.
Try

In this case the int applies to BOTH j and k so both are declared. You only get to name ONE type for declarations, so all local variables declared there must be that type. It really doesn't have to be int, it is just so useful as a counter.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic