java10以内随机数代码
时间: 2024-06-10 17:06:44 浏览: 88
您好,以下是 Java 10 及以前版本的生成随机数的代码示例:
1. 生成一个随机整数:
```java
import java.util.Random;
public class RandomNumberExample {
public static void main(String[] args) {
Random rand = new Random();
int randomNum = rand.nextInt();
System.out.println("Generated random integer: " + randomNum);
}
}
```
2. 生成指定范围内的随机整数:
```java
import java.util.Random;
public class RandomNumberExample {
public static void main(String[] args) {
Random rand = new Random();
int min = 1;
int max = 100;
int randomNum = rand.nextInt((max - min) + 1) + min;
System.out.println("Generated random integer between " + min + " and " + max + " : " + randomNum);
}
}
```
3. 生成随机浮点数:
```java
import java.util.Random;
public class RandomNumberExample {
public static void main(String[] args) {
Random rand = new Random();
double randomDouble = rand.nextDouble();
System.out.println("Generated random double: " + randomDouble);
}
}
```
希望能对您有所帮助。
阅读全文