java入门,写个方法,实现随机生成整数数组
时间: 2024-05-25 08:19:35 浏览: 11
好的,让我来为您编写一个随机生成整数数组的 Java 方法:
public static int[] generateRandomIntArray(int size, int min, int max) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = (int) (Math.random() * (max - min + 1)) + min;
}
return array;
}
在这个方法中,参数 size 表示要生成的整数数组的大小,参数 min 和 max 表示要生成的整数的范围。你可以将这个方法放到任何一个 Java 类中,然后调用该方法即可生成随机整数数组。
相关问题
java代码来实现 随机生成整数数组
以下是一个随机生成整数数组的Java代码示例:
```java
import java.util.Random;
public class RandomIntArray {
public static int[] generateIntArray(int length, int min, int max) {
int[] array = new int[length];
Random random = new Random();
for (int i = 0; i < length; i++) {
array[i] = random.nextInt(max - min + 1) + min;
}
return array;
}
public static void main(String[] args) {
int[] array = generateIntArray(10, 0, 100);
for (int i : array) {
System.out.print(i + " ");
}
}
}
```
这段代码使用了Random类来生成随机数,并将其存储在一个整数数组中。generateIntArray()方法接受三个参数:数组长度、最小值和最大值。它使用一个循环来生成数组中的每个元素,每个元素都是从最小值到最大值之间的随机整数。在main()方法中,我们使用generateIntArray()方法生成一个长度为10、最小值为0、最大值为100的整数数组,并将其打印出来。
java 随机生成整数数组的最简单方法
使用Java中的Random类可以随机生成整数数组。以下是生成长度为n,范围在[0, max)之间的整数数组的代码:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
int n = 10;
int max = 100;
int[] arr = new int[n];
Random random = new Random();
for (int i = 0; i < n; i++) {
arr[i] = random.nextInt(max);
}
System.out.println(Arrays.toString(arr));
}
}
```
这里使用了Random.nextInt(max)方法来生成0到max-1之间的整数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)