- The rare occasions in which I see that a
while () {}
would be a better fit than afor () {}
block is when the conditional test to quit it isn’t based on some defined counter. - Something like when we request an input from a user, keep asking again while the input is still invalid.
- I’ve got a sketch that does just that here:
- Besides the inner block
while ((age = readByte("Enter your age:")) < 0);
it also has a variant calleddo {} while ()
as its outer block:
byte age;
do {
while ((age = readByte("Enter your age:")) < 0);
println("Your age is:", age);
} while (readBoolean("Again?"));
- There are other fitting situations that a
while () {}
block is better. - But for now I can only think about the 1 I’ve posted above.