当前位置: 移动技术网 > IT编程>开发语言>Java > Java自学-数组 增强型for循环

Java自学-数组 增强型for循环

2019年08月23日  | 移动技术网IT编程  | 我要评论

java 中如何使用增强for循环

增强型for循环在遍历一个数组的时候会更加快捷

步骤 1 : 增强型for循环

注:增强型for循环只能用来取值,却不能用来修改数组里的值

public class helloworld {
    public static void main(string[] args) {
        int values [] = new int[]{18,62,68,82,65,9};
        //常规遍历
        for (int i = 0; i < values.length; i++) {
            int each = values[i];
            system.out.println(each);
        }
         
        //增强型for循环遍历
        for (int each : values) {
            system.out.println(each);
        }
         
    }
}

练习
(用增强型for循环找出最大的那个数)

答案

  public class helloworld {
        public static void main(string[] args) {
            int values [] = new int[]{18,62,68,82,65,9};
     
            //数组中的内容是
            for (int each : values) {
                system.out.print(each+" ");
            }
            system.out.println();
            int max = -1;
            for (int each : values) {
                if(each>max)
                    max = each;
            }
             
            system.out.println("最大的一个值是:"+max);
              
        }
    }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网