首页 > 解决方案 > 生成要打印的随机值序列。重新排序和打印。爪哇

问题描述

您好,我仍然是 Java 的初学者,我需要编写一个程序,在数组中生成 0 到 99 之间的 20 个随机值序列,打印序列,对其进行排序,然后打印排序后的序列。我有下面的代码,它非常适合我的任务。它打印一组随机值,​​然后打印排序后的一组值。您知道是否有任何方法可以简化我喜欢的代码,例如如何打印随机值?我认为可能有一种方法可以简化整个代码,但我不太确定。如果您有一些建议可以使代码看起来更干净或更简单,请告诉我。

import java.util.Arrays;

public class Array {

    public static void main(String[] args) {
        //This will create an array to hold 20 integers.
        int[] array = new int[20];
        for (int i = 0; i < array.length; i++)
        {
            array[i] = (int) (Math.random() * 99 + 1);
        }
        //This will print the random sequence of values.
        System.out.print("Random sequence of values: ");

        for (Integer i : array) {
            System.out.print(i.intValue() + " ");
        }
        System.out.println("");
        System.out.println("");
        //This will print the sorted sequence of values.
        System.out.print("Sorted sequence of values: ");
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));

    }

}

标签: java

解决方案


嗯,这样的:

new Random().ints(20,0,100).forEach(System.out::println);

或者如果你想打印排序

new Random().ints(20,0,100).sorted().forEach(System.out::println);

或者,如果你想避免流

import java.util.Arrays;
import java.util.Random;

public class Array {

    public static void main(String[] args) {
        Random random = new Random();
        //This will create an array to hold 20 integers.
        int[] array = new int[20];
        for (int i = 0; i < array.length; i++)
        {
            array[i] = random.nextInt(100);
        }
        //This will print the random sequence of values.
        System.out.println("Random sequence of values: " + Arrays.toString(array));

        Arrays.sort(array);
        //This will print the sorted sequence of values.
        System.out.println("Sorted sequence of values: " + Arrays.toString(array));
    }
}

推荐阅读