for与foreach各自的用法

首先说下foreach的书写格式:
    for(元素类型 元素名称 : 遍历数组(集合)){
      语句
     }
下面以两个具体的例子来分析for与foreach(for的加强版)各自的用法

1.对于一维数组而言
a)用for循环遍历

public class Array {
	public static void main(String[] args) {
		int[] arr1= {20,30,40};
		for(int i=0;i<arr1.length;i++) {
			System.out.print(arr1[i]+" ");
		}
	}
}

在这里插入图片描述
b)用foreach循环遍历

public class Array {
	public static void main(String[] args) {
		int[] arr1= {20,30,40};
		for(int temp: arr1) {
			System.out.print(temp+",");
		}
	}
}

在这里插入图片描述
2.对于二维数组
a)用for循环遍历

public class TwoDimensionalArray {
	public static void main(String[] args) {
		int[][] arr = new int[2][3];
		arr[0] = new int[]{1,2,3};
		arr[1] = new int[]{78,20,23};
		for(int i = 0;i < arr.length;i++){   
			//System.out.println(arr[i]);//arr中元素:2个数组的地址
			//遍历arr[0],arr中元素第一个数组
			for(int j = 0;j < arr[i].length;j++){
				System.out.print(arr[i][j] + ",");
			}
		}
	}
}

在这里插入图片描述
b)用foreach循环遍历

public class TwoDimensionalArray  {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[][] arr = {{65,6},{12,1,45,23},{0,-45,1}};
		for (int[] is : arr) {
			for (int i : is) {
				System.out.print(i + ",");
			}
		}
	}
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值