for loop without index declaration
Solution 1
another way is this one:
Integer i = 10;
while(--i>0) {
System.out.println(i);
}
When i is 0 while condition is false... so.. it will print from 9 to 1 (9 items)
Integer i = 10;
while(i-->0) {
System.out.println(i);
}
Will print from 9 to 0... (10 items);
Solution 2
The latter way is reasonable. An alternative - if you don't have any break/continue statements - would be:
while (space > 0)
{
// Code
space--;
}
zetologos
Updated on August 20, 2020Comments
-
zetologos over 3 years
So I declare a variable some where and initialize it. Now later on I need to use it to loop while its still positive so I need to decrement it. To me looping using a condition and a decrement calls for a for but for it we are missing the first part the initialization. But I don't need to initialize anything. So how do I go about that in a nice way.
for (space = space; space > 0; space--)//my first way to do it but ide doesnt like it
Second way:
for (; space > 0; space--)//my friend recommended me this way but looks kind weird
Are there more ways for me to have a loop with only condition and increment/decrement?
P.S spell check doesn't know that "decrement" is a word. I'm pretty sure it is...
-
Jon Skeet over 12 yearsThe post-decrement here will happen before the first body, so the loop will never see it in its "original" value, if you see what I mean.
-
Abdullah Jibaly over 12 yearsYep, fixed accordingly. It can be useful though in the original form if you just want to make sure the condition is satisfied. Thanks for the correction.
-
zetologos over 12 years@JonSkeet But a pre-decrement would fix that. Right?
-
Abdullah Jibaly over 12 yearsNo Jon is saying you'll never see the first value of
space
(if you need it). -
Jon Skeet over 12 years@AbdullahJibaly: The way you've got it, the "..." would still never see the original value of
space
. The "..." needs to be beforespace--
. -
zetologos over 12 yearsWell I want the original value for the first run. So wouldn't this work
while (--space > 0) ...
-
Abdullah Jibaly over 12 yearsNo it wouldn't. Of course if you liked that approach you can change your condition to
(--space >= 0)
and then take that into account in your body.