如何在Java中对数组进行排序?

huangapple go评论136阅读模式
英文:

How do I sort an array in java?

问题

以下是翻译好的部分:

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] + " ");
        }
    }
}
英文:

Input has to taken by the user. My code is given below. Why does it only output zeroes? What is the solution?

Output of the program is 0 0 0 0 (total number of input taken).

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 &lt; n; i++) {
            array[i] = input.nextInt();
        }
        Arrays.sort(array);

        for (int i = 0; i &lt; n; i++) {
            System.out.print(array[i] + &quot; &quot;);
        }
    }
}

答案1

得分: 0

你正在初始化一个包含107个值为0的数组。
所以,如果n很小,前面的元素将为0。

要查看结果,请在最后一个循环中将n替换为107,然后您将看到这些值。

英文:
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.

To see the result replace n in the last loop by 107 and you will see the values

答案2

得分: 0

你用大小为107的数组进行了初始化,这意味着在从用户那里接受输入之前,数组中最初有107个零。由于输出中有四个零,你必须输入了4个值。因此数组中有四个非零值和103个零值。当你应用 Arrays.sort 时,103个零会排在4个非零值之前。因此,当你打印n个值(在这种情况下为4个)时,你只会得到零值。
你可以使用 ArrayList,这样只有在用户输入时才会初始化数字。

英文:

You initialized an array with size 107 which implies there are 107 zeroes in the array initially before accepting the input from the user. Since there are four zeroes in the output, you must have taken 4 values for input. So there are four non-zero values and 103 zero values in the array. When you apply Arrays.sort 103 zeros comes before 4 non-zero values. Hence when you print n values (which is 4 in this case) you get only zeroes.
You could use ArrayList instead so that numbers will be initialized only when user enters it.

huangapple
  • 本文由 发表于 2020年7月28日 22:41:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63136750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定