java for each 循环 数组 对象遍历
语法
for(type itr-var : iterableobj) statement-block
看个遍历数组实例
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
遍历enum对象
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
遍历arraylist
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);
}
}