英文:
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 < n; i++) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}
}
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论