I want to ask if there are any way that you can write a while loop in Java that has the main counter inside the loop as well, that is when you exit the loop, the counter variable will also be destroyed.
For example, when we exit this loop:
for (int i = 0; i < 10; i++) {
//do something
}
the variable i is destroyed as well, thus keeping the code clean.
But for a while loop, we must create a counter variable outside the loop itself; so, when the loop exits, the counter variable still exists in the main program.
int counter = 0;
while (counter < 10) {
counter++;
}
counter--; //we can still manipulate the counter variable here
What I want to ask is: is there some way to put the counter variable inside the while loop itself, such as:
while ( (int i = 0) < 10 ) {
counter++;
}
You can put { and } around the int counter and while loop.
{
int counter = 0;
while (counter < 10) {
counter++;
}
}
// counter is inaccessible here
But this is really a lot messier than just using a for loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With