Java 生成随机不重复数字并排序:代码示例
以下代码从 1-80 中随机生成 20 个不重复的数字,从小到大排序,10 以下的补 0,使用 String.format 格式化输出:
import java.util.*;
public class RandomNumberGenerator {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
Random random = new Random();
while (list.size() < 20) {
int num = random.nextInt(80) + 1;
if (!list.contains(num)) {
list.add(num);
}
}
Collections.sort(list);
for (int num : list) {
System.out.print(String.format('%02d ', num));
}
}
}
这段代码使用了 'List' 来存储生成的随机数,使用了 'Random' 类来生成随机数,使用了 'Collections.sort' 方法来排序,使用了 'String.format' 方法来输出数字。
原文地址: https://www.cveoy.top/t/topic/jqGz 著作权归作者所有。请勿转载和采集!