我在随机 int 生成的数组上使用 Java array.sort。
结果应该是一个排序数组,但我得到的是 0 和一些随机生成的数字。
这是我的代码:
public class test {
public static void main(String[] args) {
int[] list = new int[10];
Random rand = new Random();
for (int i = 0; i < list.length; i++) {
list[i] = rand.nextInt(100);
Arrays.sort(list);
System.out.println(list[i]);
}
}
}
预期的输出应该是一个由 10 个随机整数组成的排序数组,但总是将前 5 个数字设为 0。
有人能帮忙吗?
最佳答案
看起来您在每次迭代时都对整个数组进行排序。设置值后尝试对数组进行排序和打印。
public class test {
public static void main(String[] args) {
int[] list = new int[10];
Random rand = new Random();
for (int i = 0; i < list.length; i++) {
list[i] = rand.nextInt(100);
}
Arrays.sort(list);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}
}
如果您调试应用程序,您会明白为什么每次都得到 5 个 0。
int[] list = new int[10];
产生一个 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 的数组,然后打印你对数组进行排序。因此,前 5 个(list[0]
、list[1]
、list[2]
...)将是 0
,而 list[6]
list[7]
.. 将是 rand.nextInt(100)
关于Java array.sort(arr) 输出 0 而不是 arr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52249885/