Java中怎么生成5个随机数
时间: 2024-04-23 14:28:15 浏览: 28
在Java中生成5个随机数可以使用`java.util.Random`类。以下是一个示例代码:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 5; i++) {
int randomNumber = random.nextInt();
System.out.println(randomNumber);
}
}
}
```
以上代码使用`nextInt()`方法生成随机整数。如果你需要指定随机数的范围,可以使用`nextInt(int bound)`方法,其中`bound`为上界(不包含),例如`random.nextInt(100)`会生成0到99之间的随机整数。
相关问题
java数组生成10个随机数
可以使用Java中的Random类和数组来生成10个随机数,代码如下:
```java
import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
int[] arr = new int[10];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(100); // 生成0-99的整数随机数
}
// 输出结果
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
以上代码将生成10个0-99之间的随机数,并将它们存储在一个名为arr的整数数组中。
Java中生成10位随机数
可以使用Java的Random类生成10位随机数,具体实现代码如下:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
String result = "";
for (int i = 0; i < 10; i++) {
result += random.nextInt(10);
}
System.out.println(result);
}
}
```
这段代码中,首先创建了一个Random对象,然后通过循环生成10个0到9之间的随机数,并将其拼接为一个字符串,最后输出这个字符串即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)