java练习:合并数组、生成随机数

首先准备两个数组,他俩的长度是5-10之间的随机数,并使用随机数初始化这两个数组
然后准备第三个数组,第三个数组的长度是前两个的和
通过System.arraycopy 把前两个数组合并到第三个数组中
import java.util.Random;

public class Example3 {
    public static void main(String[] args) {
        int aLength = getRandom(5,10);
        int bLength = getRandom(5,10);
        int a [] = new int[aLength];
        int b [] = new int[bLength];
        int c [] = new int[aLength+bLength];

        for(int i = 0 ; i < aLength ; i++){
            a[i] = (int) (Math.random() * 100);
        }
        for(int i = 0 ; i < bLength ; i++){
            b[i] = (int) (Math.random() * 100);
        }

        System.out.println("a:");
        //把内容打印出来
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }

        System.out.println("
b:");
        //把内容打印出来
        for (int i = 0; i < b.length; i++) {
            System.out.print(b[i] + " ");
        }

        //方法二: System.arraycopy(src, srcPos, dest, destPos, length)
        //src: 源数组
        //srcPos: 从源数组复制数据的起始位置
        //dest: 目标数组
        //destPos: 复制到目标数组的启始位置
        //length: 复制的长度
        System.arraycopy(a, 0, c, 0, aLength);
        System.arraycopy(b, 0, c, aLength, bLength);
        System.out.println("
c:");
        //把内容打印出来
        for (int i = 0; i < c.length; i++) {
            System.out.print(c[i] + " ");
        }
    }
    public static int getRandom(int min, int max){
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;
    }
}

  

原文地址:https://www.cnblogs.com/pangchunlei/p/14172772.html