Java Reference
In-Depth Information
The variable
reply
is out of scope at line 21, so the following compiler error occurs:
EnhancedFor.java:21: cannot find symbol
symbol : variable reply
location: class EnhancedFor
System.out.println(reply);
^
By the way, if we comment out line 21 and run this code, what is the output of
s
on line
20? If you are unsure, try typing in this code and running it yourself to verify the result.
I will now discuss two common uses of the nested
for
statements: iterating over
collections and nesting enhanced
for
statements.
Enhanced
for
Loops and Collections
Let's look at an example of an enhanced
for
loop that iterates over a collection. The
collection must be an object whose class implements
java.lang.Iterable
, which includes
most of the Collections API classes in the
java.util
package. The following code iterates
through a
java.util.ArrayList
. Examine the code and see if you can determine its output:
1. import java.util.ArrayList;
2.
3. public class Favorites {
4. private ArrayList<String> urls = new ArrayList<String>();
5.
6. public void showFavorites() {
7. for(String url : urls) {
8. if(url.startsWith(“http://”)) {
9. System.out.println(url);
10. } else {
11. System.out.println(“http://” + url);
12. }
13. }
14. }
15.
16. public void addFavorite(String url) {
17. urls.add(url);
18. }
19.
20. public static void main(String [] args) {
21. Favorites f = new Favorites();
Search WWH ::
Custom Search