数组的使用

数组的使用

  1. for循环(操作数组)
  2. 增强for循环(用于打印数组)
  3. 数组做参数
  4. 数组作返回值
public class ArrayDemo03 {
    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3, 4, 5};
        printArray(a);
        System.out.println("===============");
        addArray(a);
        System.out.println("===============");
        maxArray(a);
    }

    //求最大值
    private static void maxArray(int[] arrays) {
        int res = arrays[0];
        for (int i = 0; i < arrays.length; i++) {
            if (arrays[i]>res){
                res=arrays[i];
            }
        }
        System.out.println("最大值为:"+res);
    }

    //计算所有元素之和
    private static void addArray(int[] arrays) {
        int sum = 0;
        for (int i = 0; i < arrays.length; i++) {
            sum += arrays[i];
        }
        System.out.println("总和为:" + sum);
    }

    //打印数组
    private static void printArray(int[] arrays) {
        System.out.print("数组:");
        for (int i = 0; i < arrays.length; i++) {
            System.out.print(arrays[i]);
        }
        System.out.println();
    }
}
public class ArrayDemo04 {
    public static void main(String[] args) {
        int[] a = new int[]{1,2,3,4,5};

        printArray(a);
        int[] b = reverseArray(a);
        System.out.println();
        System.out.println("倒序后...");
        printArray(b);
    }

    //打印数组
    private static void printArray(int[] arrays) {
        System.out.print("数组元素为:");
        //JDK1.5,没有下标(不能操作元素,适用于遍历数组)
        for (int i : arrays) {
            System.out.print(i+"");
        }
    }


    //数组倒序
    private static int[] reverseArray(int[] arrays) {
        int[] result = new int[arrays.length];

        for (int i = arrays.length-1; i >=0 ; i--) {//反着读
            result[(arrays.length-1)-i] = arrays[i];
        }

       /* //反转操作
        for (int i = 0,j = result.length-1; i <arrays.length ; i++,j--) {
            result[j] = arrays[i];
        }*/
        return result;
    }
}
posted @ 2020-03-25 13:52  shimmernight  阅读(100)  评论(0编辑  收藏  举报