java for each 语句_java For Each 循环语句的使用方法

for each是jdk5.0新增加的一个循环结构,可以用来以此处理数组中的每个元素(其他类型的元素集合也可以)而不用为指定下标而分心。

格式如下

for(type itr-var : iterableObj) statement-block

定义一个变量用于暂存集合中的每一个元素,并执行相应的语句(当然,也可以是语句块)。集合表达式必须是一个数组或者是一个实现了lterable接口的类(例如ArrayList)对象。

例如:

public class ClsTest {

public static void main(String[] args) {

int[] a=new int[10];

for(int b:a){

System.out.println(b);

}  }  }

对于集合类型和数组类型的,我们都可以通过foreach语法来访问它。上面的例子中,以前我们要依次访问数组,挺麻烦:

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();

}

}

现在只需下面简单的语句即可:

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);

}

}

}

对集合的访问效果更明显。以前我们访问集合的代码:

import java.util.ArrayList;

public class MainClass {

public static void main(String args[]) {

ArrayList list = new ArrayList();

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);

}

}

另一种方法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值