Home

Looping in Style: Enhanced for Loops to Step through Java’s Array Values

|
|  Updated:  
2017-10-13 11:10:39
Java Essentials For Dummies
Explore Book
Buy On Amazon
You can make an enhanced for loop to step through a bunch of values, including an array’s values. Let’s take a look at an enhanced for loop that steps through an array’s values.

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.

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.

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:

for (int roomNum = 0; roomNum < 10; roomNum++) {

guestsIn[roomNum] = diskScanner.nextInt();

}

Turn this traditional for loop into an enhanced for loop, and you get the following misleading code:

for (int howMany : guestsIn) {

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.

About This Article

This article is from the book: 

About the book author: