java - 生成要打印的随机值序列。重新排序和打印。爪哇
问题描述
您好,我仍然是 Java 的初学者,我需要编写一个程序,在数组中生成 0 到 99 之间的 20 个随机值序列,打印序列,对其进行排序,然后打印排序后的序列。我有下面的代码,它非常适合我的任务。它打印一组随机值,然后打印排序后的一组值。您知道是否有任何方法可以简化我喜欢的代码,例如如何打印随机值?我认为可能有一种方法可以简化整个代码,但我不太确定。如果您有一些建议可以使代码看起来更干净或更简单,请告诉我。
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
//This will create an array to hold 20 integers.
int[] array = new int[20];
for (int i = 0; i < array.length; i++)
{
array[i] = (int) (Math.random() * 99 + 1);
}
//This will print the random sequence of values.
System.out.print("Random sequence of values: ");
for (Integer i : array) {
System.out.print(i.intValue() + " ");
}
System.out.println("");
System.out.println("");
//This will print the sorted sequence of values.
System.out.print("Sorted sequence of values: ");
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}
解决方案
嗯,这样的:
new Random().ints(20,0,100).forEach(System.out::println);
或者如果你想打印排序
new Random().ints(20,0,100).sorted().forEach(System.out::println);
或者,如果你想避免流
import java.util.Arrays;
import java.util.Random;
public class Array {
public static void main(String[] args) {
Random random = new Random();
//This will create an array to hold 20 integers.
int[] array = new int[20];
for (int i = 0; i < array.length; i++)
{
array[i] = random.nextInt(100);
}
//This will print the random sequence of values.
System.out.println("Random sequence of values: " + Arrays.toString(array));
Arrays.sort(array);
//This will print the sorted sequence of values.
System.out.println("Sorted sequence of values: " + Arrays.toString(array));
}
}
推荐阅读
- kubernetes - Kubernetes 网络模型 vs. 网络插件 vs. 网络策略
- ffmpeg - FFmpeg 的 GIF 叠加层闪烁
- logback - Logback:翻转不会删除过期的日志
- python - 保存结果数独回溯
- sql - 使用另一个表中的条件查询一个 SQL 表
- java - 应用程序暂停时如何避免工作人员运行 - android
- audio - 在 ffmpeg 中规范化音频 - 如何?
- html - 如何在primefaces inputText或inputNumber中添加图像?
- python-3.x - 在 3d 体积内创建一个 3d 圆柱体
- sql - Oracle如何对时间序列进行分类?