java遍历数组

来源:互联网 发布:手机淘宝怎么删除账号 编辑:程序博客网 时间:2024/06/05 08:07

1、遍历数组就是获取数组中的每个元素。通常遍历数组都是使用for循环来实现。

      遍历二维数组需要使用双层for循环,通过数组的length属性可获得数组的长度。

  public class Trap {    public static void main(String[] args){//主方法        int b[][] = new int[][]{{1},{2,3},{4,5,6}};//定义二维数组        for(int i = 0; i<b.length; i++){            for(int j = 0; j<b[i].length; j++){//循环遍历二维数组的每一个元素                System.out.print(b[i][j]);//将数组中的元素输出            }            System.out.println();//输出空格        }    }}

2、在遍历数组时使用foreach语句可能会更简单。下面的实例用foreach语句遍历二维数组。


public class Tautog {//创建类public static void main(String[] args){//主方法int arr[][] = {{4,3},{2,1}};//定义二维数组System.out.println("数组中的元素是:"); for(int x[]:arr){//外层循环变量为一维数组for(int e:x){ //循环遍历每一个数组元素if(e == arr[arr.length-1][x.length-1]){//判断变量是否是二维数组的最后一个元素System.out.print(e);//输出二维数组的最后一个元素}else{//如果不是二维数组最后一个元素System.out.print(e+"、");}}}}}