猿问

如何使用 Arrays.sort 输出

我正在尝试使用 Arrays.sort 按升序和降序打印 10,000 个随机数,然后输出它。如果我这样尝试,它不会给出正确的输出。


import java.util.*;

import java.util.Random;


public class QuestionFour 

{

    public static void main(String[] args) 

    {

        int arr[] = new int[10000];

        Random rand = new Random();


        for (int i=0; i<10000; i++)

        {

            arr[i] = rand.nextInt( 100 ) + 1;

            Arrays.sort(arr);

            System.out.println(arr);

        }

    }


}


慕森卡
浏览 207回答 2
2回答

慕仙森

Arrays.sort()与输出没有任何关系,它只是sorts一个数组让你的循环填充数组,之后,sort和print它与Arrays.toString()int arr[] = new int[10000];Random rand = new Random();for (int i=0; i<10000; i++){&nbsp; &nbsp; arr[i] = rand.nextInt( 100 ) + 1;}Arrays.sort(arr);System.out.println(Arrays.toString(arr));逆序排序:您可以使用Arrays.sort(arr, Comparator.reverseOrder());,但这需要一个对象数组,它需要一个Integer arr[] = new Integer[10000];而不是int使用 aList<Integer>而不是 en 数组,它会更容易操作List<Integer> list = new ArrayList<>();Random rand = new Random();for (int i = 0; i < 10000; i++) {&nbsp; &nbsp; list.add(rand.nextInt(100) + 1);}list.sort(Comparator.reverseOrder());System.out.println(list);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//[100, 100, 100, 100, 100, 100, 100, 100 ...&nbsp;

幕布斯7119047

您需要Arrays.sort(arr);在 for 循环之外放置并创建另一个循环以在排序后打印数组。您的代码应如下所示:import java.util.*;import java.util.Random;public class QuestionFour&nbsp;{&nbsp; &nbsp; public static void main(String[] args)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int arr[] = new int[10000];&nbsp; &nbsp; &nbsp; &nbsp; Random rand = new Random();&nbsp; &nbsp; &nbsp; &nbsp; for (int i=0; i<10000; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr[i] = rand.nextInt( 100 ) + 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Arrays.sort(arr);&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(arr[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答