<Java>数组(三)遍历数组

遍历数组

java中遍历数组的方式主要有
1、for
2、while
3、do…while
4、增强for循环(foreach)

遍历一维数组

通常都是使用for循环,让循环变量i从0到<数组的length,这样循环体内最大的i正好是数组最大的有效下标

public class Test {
    public static void main(String[] args) {
	//一维数组
     	int [] x =new int[3];
       		x[0] = 1;
       		x[1] = 2;
       		x[2] = 3;

	// for循环遍历数组
          for(int a = 0; a<x.length; a++){
                System.out.print(x[a]);//输出结果为123
          }

	// 增强for循环  s遍历所有数组
	//for(数据类型 变量:数组(集合)){
                    //输出(变量);
	//}
          for(int a:x){//进行遍历
                System.out.println(a);//输出结果为123
          }

	// while形式遍历数组
            int a=0;
            while (a<x.length){
                System.out.println(x[a]);//输出结果为123
                a++;
        }

	// do...while形式遍历数组
          int b=0;
          do{
              System.out.println(x[b]);//输出结果为123
              b++;
          }while(b<x.length);
    }	
}

遍历二维数组

public class Test {
	 public static void main(String[] args) {
	    int[][] x = new int[2][2];
	    x[0][0]=1;
	    x[0][1]=2;
	    x[1][0]=3;
	    x[1][1]=4;
	  
	     //  for 形式
	     for(int a=0;a<x.length;a++){
	         for(int j=0;j<x[a].length;j++){
	             System.out.println("二维数组:"+x[a][j]);
	         }
	     }
	  
	     //  增强  for形式
	     for(int[] a:x){
	         for(int k:a){
	         System.out.println("二维数组:"+k);
	         }
	     }
	  
	     //  while形式
	     int a=0;
	     while(a<x.length){
	         for(int j1=0;j1<x[a].length;j1++){
	             System.out.println("二维数组:"+x[a][j1]);
	         }
	         a++;
	     }
	  
	     //  do...while形式
	     int b=0;
	     do{
	         for(int j2=0;j2<x[b].length;j2++){
	             System.out.println("二维数组:"+x[b][j2]);
	         }
	         b++;
	     }while(b<x.length);
 	}
}	

常见错误:循环结束条件是<=数组长度,或离开循环后,继续用i的值来做数组元素的下标!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值