数组使用练习

  • For-Each循环
  • 数组作为方法入参
  • 数组作为返回值

示例:

package com.zctou.array;

public class ArrayDemo04 {
    public static void main(String[] args) {
        // 数组使用演示
        int[] nums = {1,2,3,4,5};

        // 1. 打印全部数组元素
        for (int i = 0; i <nums.length ; i++) {
            System.out.print(i+ ",");
        }
        System.out.println("\n===========");

        // 2. 计算所有元素的和
        int sum = 0;
        for (int i = 0; i <nums.length ; i++) {
            sum += nums[i];
        }
        System.out.println("数组求和:" + sum);
        System.out.println("==========");

        // 3. 查找最数组最大值
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if(max<nums[i]) {
                max = nums[i];
            }
        }
        System.out.println("数组中的最大值是:" + max);
        System.out.println("==========");

        // 4. for each 循环,JDK1.5后加入,没有下标
        for (int x:nums) {
            System.out.print(x + ",");
        }
        System.out.println("\n==========");

        // 5. 反转数组
        int[] newNums = reverse(nums);
        for (int i = 0; i <newNums.length ; i++) {
            System.out.print(newNums[i] + ",");
        }
        System.out.println("\n==========");

    }

    //定义反转数组的方法
    public static int[] reverse(int[] array) {
        int[] reverseResult = new int[array.length];
        for (int i = 0; i < array.length ; i++) {
            reverseResult[array.length-1-i] = array[i]; //注意数组下标越界
        }
        //for循环定义2个变量的用法
        /*
        for (int i = 0,j=array.length-1; i < array.length; i++,j--) {
            reverseResult[j] = array[i];
        }*/
        return reverseResult;
    }
}

输出:

0,1,2,3,4,
===========
数组求和:15
==========
数组中的最大值是:5
==========
1,2,3,4,5,
==========
5,4,3,2,1,
==========