wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Comma seperator for the FOR loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comma seperator for the FOR loop" Watch "Comma seperator for the FOR loop" New topic
Author

Comma seperator for the FOR loop

Dale DeMott
Ranch Hand

Joined: Nov 02, 2000
Posts: 515
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)


By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
CHRIS MELVIN
Greenhorn

Joined: Dec 11, 2000
Posts: 2
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

Joined: Nov 02, 2000
Posts: 515
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

Joined: Sep 29, 2000
Posts: 8521
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.

"JavaRanch, where the deer and the Certified play" - David O'Meara
 
Consider Paul's rocket mass heater.
 
subject: Comma seperator for the FOR loop
 
Similar Threads
When can you use the comma operator
for loop question
Control Statement
confusion in code
loop