java - 生成固定长度的随机数组
问题描述
我只是想更改我的代码,以便每次运行代码时都会生成一个固定长度为 100 个整数的随机数组,而不仅仅是在代码中包含一个预设数组。我对此很陌生,所以只需要一个正确方向的指南,谢谢
public class Selectionsort {
public static void main(String[] args) {
int[] numbers = {15, 8, 6, 21, 3, 54, 6, 876, 56, 12, 1, 4, 9};
sort(numbers);
printArray(numbers);
}
public static int[] sort(int[] A) {
for (int i = 0; i < A.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < A.length; j++) {
if (A[j] < A[minIndex]) {
minIndex = j;
}
}
int temp = A[minIndex];
A[minIndex] = A[i];
A[i] = temp;
}
return A;
}
public static void printArray(int[] A) {
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
解决方案
public class Selectionsort {
public static void main(String[] args) {
int[] numbers = new int[100]
Random random = new Random();
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextInt(100);
}
sort(numbers);
printArray(numbers);
}
}
上面的代码片段将帮助您为大小为 100 的数组创建一个介于 1 到 100 之间的随机数。
推荐阅读
- java - Geocode API 在 HTTP 响应中返回 null
- sql - XMLAGG 在结果中重复
- sockets - c++ 创建的套接字值非常大,例如 590258032 等
- xamarin - Xamarin Android 自定义 NOTICE 文件
- c++ - opengl light减少反射
- perl - Perl:如果 IPC::Run 死了,则从进程中检索输出
- php - PHP,从关联多维数组中的特定 $key 中获取 $value
- sql - 在一个视图中运行两个选择语句?
- sql - Acumatica GI 库存周转率
- xamarin.forms - Xamarin.Forms v3 中的 MasterDetail + 从右到左