首页 > 编程语言 > 详细

数组的使用

时间:2021-07-02 00:47:33      阅读:17      评论:0      收藏:0      [点我收藏+]
  1. for循环
  2. for each的使用
  3. 数组排序
  4. 数组作为方法参数的使用
  5. 数组作为返回值的使用

遍历数组

package array;

import java.util.Arrays;

public class ArrayDemo02 {
    public static void main(String[] args) {
        // for循环
        int[] nums = {1, 2, 3, 4, 5};
        for (int i = 0; i < nums.length; i++) {
            System.out.println("for循环打印数组" + nums[i]);
        }
        System.out.println("=====================");
        for (int num : nums) {
            System.out.println("for each方式打印数组==" + num);
        }
        System.out.println("=====================");
        System.out.println("Arrays.toString()打印数组==>" + Arrays.toString(nums));
        System.out.println("=====================");
        int maxValue = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > maxValue) {
                maxValue = nums[i];
            }
        }
        System.out.println("nums数组的最大值为==>" + maxValue);
        System.out.println("=====================");
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        System.out.println("nums数组的和为==>" + total);
    }
}

参数和返回值

package array;

import java.util.Arrays;

public class ArrayDemo03 {
    public static void main(String[] args) {
        int[] lists = {100, 101, 102, 103, 104};
        System.out.println(Arrays.toString(reserveArray(lists)));
        //  [104, 103, 102, 101, 100]
    }

    /**
     * 反转数组
     *
     * @param arrays
     */
    public static int[] reserveArray(int[] arrays) {
        int[] data = new int[arrays.length];
        for (int i = 0, j = arrays.length - 1; i < arrays.length; i++, j--) {
            data[i] = arrays[j];
        }
        return data;
    }
}

小结

for循环可以获取到索引 for each不行 、
使用Arrays.toString()可以快速打印数组内容

数组的使用

原文:https://www.cnblogs.com/juanbao/p/14954476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!