首页 > 解决方案 > 生成固定长度的随机数组

问题描述

我只是想更改我的代码,以便每次运行代码时都会生成一个固定长度为 100 个整数的随机数组,而不仅仅是在代码中包含一个预设数组。我对此很陌生,所以只需要一个正确方向的指南,谢谢

public class Selectionsort {
    public static void main(String[] args) {
        int[] numbers = {15, 8, 6, 21, 3, 54, 6, 876, 56, 12, 1, 4, 9};
        sort(numbers);
        printArray(numbers);
    }

    public static int[] sort(int[] A) {
        for (int i = 0; i < A.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < A.length; j++) {
                if (A[j] < A[minIndex]) {
                    minIndex = j;
                }
            }
            int temp = A[minIndex];
            A[minIndex] = A[i];
            A[i] = temp;
        }
        return A;
    }

    public static void printArray(int[] A) {
        for (int i = 0; i < A.length; i++) {
            System.out.println(A[i]);
        }
    }
}

标签: javaarraysrandom

解决方案


public class Selectionsort {
    public static void main(String[] args) {
        int[] numbers = new int[100]
        Random random = new Random();

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = random.nextInt(100);
        }
        sort(numbers);

        printArray(numbers);
    }
}

上面的代码片段将帮助您为大小为 100 的数组创建一个介于 1 到 100 之间的随机数。


推荐阅读