码迷,mamicode.com
首页 > 编程语言 > 详细

Java for循环使用方法

时间:2014-11-05 00:24:15      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   使用   java   for   sp   strong   

Java中for循环多了一种写法——foreach写法(一般只用于遍历整个数组,不用担心越界等问题)。

1.1)常规写法:

package foreach.main.sn;

public class Foreach {

	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5};
		for (int i = 0; i < arr.length; ++i){
			System.out.println(arr[i]);
		}
	}
}
1.2)foreach写法:(注意这里的 t 是一个临时变量值,用来保存当前遍历到的数组值,如果需要改变数组的值,则不能用该方法遍历)

package foreach.main.sn;

public class Foreach {

	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5};
		for (int t : arr){
			System.out.println(t);
		}
	}
}

bubuko.com,布布扣


2)使用foreach遍历二维数组:

package foreach.main.sn;

public class Foreach {

	public static void main(String[] args) {
		
		int[][] arr2 = {{1,2,3},{4,5},{6,7,8}};
		
		for (int t1[] : arr2){
			for (int t2 : t1){
				System.out.print(t2);
			}
			System.out.println();
		}
	}
}

bubuko.com,布布扣

原文地址:http://blog.csdn.net/qingdujun/article/details/40799561


Java for循环使用方法

标签:style   blog   http   ar   使用   java   for   sp   strong   

原文地址:http://blog.csdn.net/qingdujun/article/details/40799561

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!