for
To see such a loop, start with this code. The loop looks something like this:
for (int roomNum = 0; roomNum < 10; roomNum++) {
out.println(guestsIn[roomNum]);
}
To turn this into an enhanced for loop, you make up a new variable name. (What about the name howMany? Nice name.) Whatever name you choose, the new variable ranges over the values in the guestsIn array.
howMany
guestsIn
for (int howMany : guestsIn) {
out.println(howMany);
This enhanced loop uses this format.
for (<em>TypeName variableName</em> : <em>RangeOfValues</em>) {
<em>Statements</em>
The RangeOfValues can belong to an enum type. Here, the RangeOfValues belongs to an array.
RangeOfValues
Enhanced for loops are nice and concise. But don’t be too eager to use enhanced loops with arrays. This feature has some nasty limitations. For example, the new howMany loop doesn’t display room numbers. Room numbers are avoided because the room numbers in the guestsIn array are the indices 0 through 9. Unfortunately, an enhanced loop doesn’t provide easy access to an array’s indices.
And here’s another unpleasant surprise. Start with the following loop:
guestsIn[roomNum] = diskScanner.nextInt();
Turn this traditional for loop into an enhanced for loop, and you get the following misleading code:
howMany = diskScanner.nextInt(); <strong>/Don't do this</strong>
The new enhanced for loop doesn’t do what you want it to do. This loop reads values from an input file and then dumps these values into the garbage can. In the end, the array’s values remain unchanged.
It’s sad but true. To make full use of an array, you have to fall back on Java’s plain old for loop.
Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.