/** * @author WanJl * @version 1.0 * @title Demo02 * @description foreach迭代-增强for循环 * @create 2026/7/16 */ public class Demo02 { public static void main(String[] args) { //我们之前使用的for循环,是for(int i=0;i<10;i++) //可以使用增强for循环--foreach,作用和for循环一样 //主要是用来进行数组遍历 /* 格式: for(数据类型 变量 : 数组名){ 代码块 } */ int[] arr = {1, 2, 3, 4, 5, 6, 8}; for (int a : arr) { System.out.print(a + " "); } System.out.println(); /* foreach 遍历的数组,无法获取索引值,所以只适合遍历全部元素。想要获取某个索引位置的元素,需要for循环 */ int[] arr01 = {1, 3}; int[] arr02 = {4, 5, 6}; int[] arr03 = {7, 8, 9, 15}; int[][] arr2 = {arr01, arr02, arr03}; for (int[] a : arr2) { //外层foreach for (int a1 : a) { //内层foreach System.out.print(a1 + " "); } System.out.println(); } } }