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

Java for循环使用方法

时间:2014-11-05 07:01:23      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   os   使用   java   for   

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

1.1)常规写法:

  1. package foreach.main.sn;  
  2.   
  3. public class Foreach {  
  4.   
  5.     public static void main(String[] args) {  
  6.         int[] arr = {1,2,3,4,5};  
  7.         for (int i = 0; i < arr.length; ++i){  
  8.             System.out.println(arr[i]);  
  9.         }  
  10.     }  
  11. }  

1.2)foreach写法:(注意这里的 t 是一个临时变量值,用来保存当前遍历到的数组值,如果需要改变数组的值,则不能用该方法遍历)

  1. package foreach.main.sn;  
  2.   
  3. public class Foreach {  
  4.   
  5.     public static void main(String[] args) {  
  6.         int[] arr = {1,2,3,4,5};  
  7.         for (int t : arr){  
  8.             System.out.println(t);  
  9.         }  
  10.     }  
  11. }  

bubuko.com,布布扣


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

  1. package foreach.main.sn;  
  2.   
  3. public class Foreach {  
  4.   
  5.     public static void main(String[] args) {  
  6.           
  7.         int[][] arr2 = {{1,2,3},{4,5},{6,7,8}};  
  8.           
  9.         for (int t1[] : arr2){  
  10.             for (int t2 : t1){  
  11.                 System.out.print(t2);  
  12.             }  
  13.             System.out.println();  
  14.         }  
  15.     }  
  16. }  

bubuko.com,布布扣

Java for循环使用方法

标签:style   blog   http   io   ar   os   使用   java   for   

原文地址:http://www.cnblogs.com/yuyanbian/p/4075308.html

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