简体   繁体   English

如何对 java 中的数组进行排序?

[英]How do I sort an array in java?

Input has to taken by the user.输入必须由用户进行。 My code is given below.我的代码如下。 Why does it only output zeroes?为什么它只有 output 归零? What is the solution?解决办法是什么?

Output of the program is 0 0 0 0 (total number of input taken).程序的 Output 为0 0 0 0 (输入的总数)。

import java.util.Arrays;
import java.util.Scanner;

public class atlast {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();
        int[] array = new int[107];
        for (int i = 0; i < n; i++) {
            array[i] = input.nextInt();
        }
        Arrays.sort(array);

        for (int i = 0; i < n; i++) {
            System.out.print(array[i] + " ");
        }
    }
}
int[] array = new int[107];

You are initializing a table that contains 107 value of 0. So, if the n is small, the first elements will be 0.您正在初始化一个包含 107 值为 0 的表。因此,如果n很小,则第一个元素将为 0。

To see the result replace n in the last loop by 107 and you will see the values要查看结果,将最后一个循环中的 n 替换为 107,您将看到值

You initialized an array with size 107 which implies there are 107 zeroes in the array initially before accepting the input from the user.您初始化了一个大小为 107 的数组,这意味着在接受用户输入之前,数组中最初有 107 个零。 Since there are four zeroes in the output, you must have taken 4 values for input.由于 output 中有四个零,因此您必须取 4 个值作为输入。 So there are four non-zero values and 103 zero values in the array.所以数组中有四个非零值和103个零值。 When you apply Arrays.sort 103 zeros comes before 4 non-zero values.当您应用Arrays.sort 103 个零位于 4 个非零值之前。 Hence when you print n values (which is 4 in this case) you get only zeroes.因此,当您打印 n 个值(在这种情况下为 4)时,您只会得到零。 You could use ArrayList instead so that numbers will be initialized only when user enters it.您可以改用ArrayList ,这样只有在用户输入时才会初始化数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM