// Search an array using for-each style for.
class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
// use for-each style for to search nums for val
for(int x : nums) {
if(x == val) {
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}
}
The for-each style for is an excellent choice in this application because searching an
unsorted array involves examining each element in sequence. (Of course, if the array were
sorted, a binary search could be used, which would require a different style loop.) Other
types of applications that benefit from for-each style loops include computing an average,
finding the minimum or maximum of a set, looking for duplicates, and so on.
Although we have been using arrays in the examples in this chapter, the for-each style
for is especially useful when operating on collections defined by the Collections Framework,
which is described in Part II. More generally, the for can cycle through the elements of any
collection of objects, as long as that collection satisfies a certain set of constraints, which are
described in Chapter 17.
Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop may
be inside another. For example, here is a program that nests for loops:
// Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home