增强型for 循环局限,及多维的遍历

来源:互联网 发布:科颜氏洗发水知乎 编辑:程序博客网 时间:2024/06/06 00:15
     增强型for 循环与 for 循环
    优势:
        增强型for循环 比for循环 更简洁。
    局限:
        1、增强型for循环只能遍历数组的所有元素,不能对某个区间进行遍历
        2、增强型for循环只能顺序遍历
        3
public class ForEach {public static void main(String[] args) {int[] a = {1, 2, 3, 4, 5};//逆序的访问数组for (int i = a.length -1; i >= 0; i--){}//只能顺序的进行遍历。for (int i : a){}//访问数组的一部分元素for (int i = 2; i < a.length; i++){}//在循环中改变数组元素的值for (int i = 0; i < a.length; i++) {a[i] = i + 10;}for (int i : a){//没有索引值}int[] b = {1, 2, 3, 4, 5};for (int i : b){i = 100;}for (int i : b){System.out.print(i + " ");}}}

遍历

public class MultiArray {public static void main(String[] args) {//int[] x = new int[5];int[][] x = new int[3][4];int[][] y = {{1, 2}, {2, 3}, {3, 4}};int[][] z = new int[][] {{1, 2}, {2, 3}, {3, 4}};//不规则多维数组//先分配高维。int[][] k = new int[3][];k[0] = new int[3];k[1] = new int[4];k[2] = new int[5];//遍历多维数组//传统for循环for (int i = 0; i < y.length; i++) {for (int j = 0; j < y[i].length ; j++){System.out.print(y[i][j] + " ");}System.out.println();}//增强型for循环for (int[] i : y) {for (int j : i) {System.out.print(j + " ");}System.out.println();}}}




0 0
原创粉丝点击