java中math.random与random类
时间: 2023-08-16 16:12:23 浏览: 122
在Java中,有两种不同的方式可以生成随机数:使用Math类的random()方法和使用java.util.Random类。
1. Math类的random()方法:
Math类是Java内置的数学类,其中有一个静态方法random(),用于生成一个0到1之间的随机浮点数。具体使用方法如下:
```java
double randomNum = Math.random(); // 生成一个0到1之间的随机浮点数
```
这个方法会返回一个大于等于0且小于1的伪随机浮点数。如果你需要生成其他范围的随机数,可以使用乘法和加法进行缩放和偏移。例如,如果你想生成一个0到100之间的随机整数,可以使用以下代码:
```java
int randomInt = (int) (Math.random() * 101); // 生成一个0到100之间的随机整数
```
注意:使用Math类的random()方法生成的随机数是伪随机数,每次程序运行时都会生成相同的随机数序列。如果需要更高质量的随机数,可以考虑使用Random类。
2. Random类:
Random类是Java提供的随机数生成器类,位于java.util包中。使用Random类可以生成各种类型的随机数,包括整数、浮点数、布尔值等。以下是一个使用Random类生成随机整数的示例:
```java
import java.util.Random;
// 创建Random对象
Random random = new Random();
// 生成一个0到100之间的随机整数
int randomInt = random.nextInt(101);
// 打印随机整数
System.out.println(randomInt);
```
Random类的nextInt()方法用于生成一个指定范围内的随机整数。在上述示例中,nextInt(101)会生成一个0到100之间的随机整数。
总结:Math类的random()方法适用于简单的随机数生成需求,而Random类适用于更复杂的随机数生成需求,可以生成不同类型的随机数,并且具有更好的随机性。
阅读全文
相关推荐
















