The For-Each Version of the for Loop
The general form of the for-each version of the for is shown here: | |
| |
The object referred to by iterableObj must be an array or an object that implements the new Iterable interface. |
The for-each loop is essentially read-only
public class MainClass {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
The for each loop for an enum data type
for (type identifier : iterable_expression) {
// statements
}
public class MainClass {
enum Season {
spring, summer, fall, winter
}
public static void main(String[] args) {
for (Season season : Season.values()) {
System.out.println(" The season is now " + season);
}
}
}
The season is now spring The season is now summer The season is now fall The season is now winter
Using the For-Each Loop with Collections: ArrayList
For-Each Loop can be used to any object that implements the Iterable interface. This includes all collections defined by the Collections Framework, import java.util.ArrayList;
public class MainClass {
public static void main(String args[]) {
ArrayList<Double> list = new ArrayList<Double>();
list.add(10.14);
list.add(20.22);
list.add(30.78);
list.add(40.46);
double sum = 0.0;
for(double itr : list)
sum = sum + itr;
System.out.println(sum);
}
}
Use a for-each style for loop
public class MainClass {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
Value is: 1 Value is: 2 Value is: 3 Value is: 4 Value is: 5 Value is: 6 Value is: 7 Value is: 8 Value is: 9 Value is: 10 Summation: 55
Using 'for each' to loop through array
public class MainClass {
public static void main(String[] arg) {
char[] vowels = { 'a', 'e', 'i', 'o', 'u'};
for(char ch: vowels){
System.out.println(ch);
}
}
}
e
i
o
public class MainClass { Value is: 1 Value is: 2 Value is: 3 Value is: 4 Value is: 5 Value is: 2 Value is: 4 Value is: 6 Value is: 8 Value is: 10 Value is: 3 Value is: 6 Value is: 9 Value is: 12 Value is: 15 Summation: 90 Using break with a for-each-style for public class MainClass { | |
http://www.java2s.com/Tutorial/
Java/0080__Statement-Control/Usingbreakwithaforeachstylefor.htm
No comments:
Post a Comment